Include from displayed file or folder that contains - php

When using php do you set your path in reference to the files directory or from the page it is displayed from.
For example:
index.php is the home page of course
Directory structure.
index.php
includes > footer.php, header.php
product > product.php [blueproduct] > blueproduct.php
storescripts > connect_to_mysql.php, more.php
=================================================
Inside of footer I have a script that is not working on every page. Its a newsletter script to collect info. This is the code I'm using within my included footer.php:
</div>
<div class="footer">
<div class="wideNewsletter">
<div class="wrapNewsletter">
<div class="newsletterIntro"><b>NEWSLETTER SIGN UP</b></div>
<div class="newsletterForm">
<?php
$name = "";
$email = "";
$msg_to_user = "";
if ($_POST['name'] != "") {
include "../storescripts/connect_to_mysql.php";
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<div class="warning"><ul><li>Please type an email address ' . $name . '.</li></ul></div><br /><br />';
} else if ($numRows > 0) {
$msg_to_user = '<div class="warning"><ul><li>' . $email . ' is already in the system.</li></ul></div><br /><br />';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime)
VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = '<div class="success"><ul><li>Thanks ' . $name . ', hope you find what you want!</li></ul></div><br /><br />';
$name = "";
$email = "";
}
$message = 'Name: ' . $_POST['name'] . ' Email: ' . $_POST['email'];
mail('newproducts#moniquetrinidadjewelry.com', 'New Newsletter Sign Up at Monique Trinidad Jewelry', $message);
}
?>
<form style="width:430px;" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset style="text-align:left;padding:0px;border:0px;">
Name:
<input name="name" type="text" maxlength="36" value="<?php echo $name; ?>" />
Email:
<input name="email" type="text" maxlength="36" value="<?php echo $email; ?>" />
<input type="image" src="https://www.moniquetrinidadjewelry.com/images/new-images/green-bullet.png" border="0" name="mySubmitBtn" type="submit" value="Submit">
</fieldset>
</form></div>
<div style="position:absolute;top:120px;"><?php echo $msg_to_user; ?></div>
<div class="newsletterExplain">Receive product updates. Remember only one of each!</div>
</div>
</div><!--wide newletter end-->
<div class="wrapFooter">
<div class="tearOneFooter">
<div class="footerColumnList">
<div class="footerTitles">Connect With Us</div>
<div class="footerLists">
<ul>
<li>Connect With Monique!</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
<div class="footerColumnList">
<div class="footerTitles">Information</div>
<div class="footerLists">
<ul>
<li>About Us</li>
<li>Packaging</li>
<li>Terms & Conditions</li>
</ul>
</div>
</div>
<!--Seperate Information Column from Shipping and Returns Column-->
<div class="footerColumnList">
<div class="footerTitles">Shipping and Returns</div>
<div class="footerLists">
<ul>
<li><a href="https://www.moniquetrinidadjewelry.com/return-policy.php">Orders and Returns<a/></li>
<li>Secure Shopping</li>
<li></li>
</ul>
</div>
</div>
<!--Seperate Shipping and Returns Column from Services & Support Column-->
<div class="footerColumnList">
<div class="footerTitles">Hours Of Operation</div>
<div class="footerLists">
<ul>
<li>We are a 24/7 <br />Online Establishment!<br />(US Based)</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
</div>
<!--Beging SecondTearFooterArea-->
<div class="tearTwoFooter">
<!--<div class="signUpNewsLetter"><img src="https://www.moniquetrinidadjewelry.com/images/news_letter_temp_IMG.png" alt="newsletter" /></div>-->
<div class="paymentOptions"><img src="https://www.moniquetrinidadjewelry.com/images/payment_options_temp.png" alt="payment options" /></div>
<div class="twitter"><img src="https://www.moniquetrinidadjewelry.com/images/twitter_temp.png" alt="twitterLink" /></div>
</div>
</div>
</div>
</div>
This is working within the [blueproduct] directory from the product directory, but not the index.php.
I have another issue as well, but I believe better practice would be to open another question after I've done research on the issue correct? If not let me know and I'll edit this original message.
================================================================================
Edits and Additions Below
I have everything configured and I believe I can elminiate this as the issue. I'm really stumped on this one. The link to give you a better idea of what I mean is http://www.moniquetrinidadjewerly.com . If you go there and try the form it doesn't process, but that same form if you select 'necklace' within the navigation you can see works fine and runs correctly. Here is the updated footer.php file below to include changes for abs path.
</div>
<div class="footer">
<div class="wideNewsletter">
<div class="wrapNewsletter">
<div class="newsletterIntro"><b>NEWSLETTER SIGN UP</b></div>
<div class="newsletterForm">
<?php
$name = "";
$email = "";
$msg_to_user = "";
if ($_POST['name'] != "") {
include_once(DOC-ROOT."/storescripts/connect_to_mysql.php");
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<div class="warning"><ul><li>Please type an email address ' . $name . '.</li></ul></div><br /><br />';
} else if ($numRows > 0) {
$msg_to_user = '<div class="warning"><ul><li>' . $email . ' is already in the system.</li></ul></div><br /><br />';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime)
VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = '<div class="success"><ul><li>Thanks ' . $name . ', hope you find what you want!</li></ul></div><br /><br />';
$name = "";
$email = "";
}
$message = 'Name: ' . $_POST['name'] . ' Email: ' . $_POST['email'];
mail('newproducts#moniquetrinidadjewelry.com', 'New Newsletter Sign Up at Monique Trinidad Jewelry', $message);
}
?>
<form style="width:430px;" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset style="text-align:left;padding:0px;border:0px;">
Name:
<input name="name" type="text" maxlength="36" value="<?php echo $name; ?>" />
Email:
<input name="email" type="text" maxlength="36" value="<?php echo $email; ?>" />
<input type="image" src="https://www.moniquetrinidadjewelry.com/images/new-images/green-bullet.png" border="0" name="mySubmitBtn" type="submit" value="Submit">
</fieldset>
</form></div>
<div style="position:absolute;top:120px;"><?php echo $msg_to_user; ?></div>
<div class="newsletterExplain">Receive product updates. Remember only one of each!</div>
</div>
</div><!--wide newletter end-->
<div class="wrapFooter">
<div class="tearOneFooter">
<div class="footerColumnList">
<div class="footerTitles">Connect With Us</div>
<div class="footerLists">
<ul>
<li>Connect With Monique!</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
<div class="footerColumnList">
<div class="footerTitles">Information</div>
<div class="footerLists">
<ul>
<li>About Us</li>
<li>Packaging</li>
<li>Terms & Conditions</li>
</ul>
</div>
</div>
<!--Seperate Information Column from Shipping and Returns Column-->
<div class="footerColumnList">
<div class="footerTitles">Shipping and Returns</div>
<div class="footerLists">
<ul>
<li><a href="https://www.moniquetrinidadjewelry.com/return-policy.php">Orders and Returns<a/></li>
<li>Secure Shopping</li>
<li></li>
</ul>
</div>
</div>
<!--Seperate Shipping and Returns Column from Services & Support Column-->
<div class="footerColumnList">
<div class="footerTitles">Hours Of Operation</div>
<div class="footerLists">
<ul>
<li>We are a 24/7 <br />Online Establishment!<br />(US Based)</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
</div>
<!--Beging SecondTearFooterArea-->
<div class="tearTwoFooter">
<!--<div class="signUpNewsLetter"><img src="https://www.moniquetrinidadjewelry.com/images/news_letter_temp_IMG.png" alt="newsletter" /></div>-->
<div class="paymentOptions"><img src="https://www.moniquetrinidadjewelry.com/images/payment_options_temp.png" alt="payment options" /></div>
<div class="twitter"><img src="https://www.moniquetrinidadjewelry.com/images/twitter_temp.png" alt="twitterLink" /></div>
</div>
</div>
</div>
</div>
The config.inc.php file is located within the main directory and it reads :
<?php
define("Monique trinidad Jewelry","My Website");
define("DOC_ROOT","/home3/onlinfr7/public_html");
define("URL","https://www.moniquetrinidadjewelry.com");
?>
I'm not sure where the issue is occurring or what exactly is happening with the homepage(index.php) newsletter form in the footer. Why it works in one page, but not the other. It seems that path may not be the issue as I first thought. Any advice?

there's the current working directory, which you can get with getcwd(). THAT'S the path that everything will be relative to in any file operations you perform. By default it will be the directory that your main script is executed from.
Whether you go relative to that, or relative to something else, or just absolute on everything is up to you. There's no right/wrong answer - just whatever's easiest for YOU to maintain.

What I like to do that makes things easier when including other files is create a config file and include that in the main file or header like index.php
So this might be my config file called config.inc.php
<?php
define("SITENAME","My Website");
define("DOC_ROOT","/home/username/webroot");
define("URL","http://www.example.com");
?>
I include this config file in my index.php like
include("/home/username/webroot/config.inc.php");
Then I can use DOC_ROOT whenever I want to include another file somewhere and it will always have the full absolute path so that you know it's included.
e.g. include_once(DOC_ROOT."/storescripts/connect_to_mysql.php");

Related

PHP text input to .txt file

I tried to make a simple PHP program that writes text from an input field and puts it in a .txt file. What is wrong with my code? It doesn't leave spaces between items and copies the previous item and doubles it. The file is called email.txt . Here is the code:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$file = fopen("email.txt", "r+") or die("<h1>Eroarea 1</h1>"); //In caz ca fisierul nu este gasit
$s = fread($file, filesize("email.txt"));
$s = $name . "\n";
fputs($file, $s) or die("<h1>Eroarea 2</h1>"); //In caz ca server-ul nu poate fi contactat
fclose($file);
echo "<h1></h1>";
} ?>
<section id="five" class="wrapper style2 special fade">
<div class="container">
<header>
<h2>Writer</h2>
<p>Put text here</p>
</header>
<form method="post" action="#" class="container 50%" onSubmit="post">
<div class="row uniform 50%">
<div class="8u 12u$(xsmall)"><input type="text" name="name" placeholder="Email" /></div>
<div class="4u$ 12u$(xsmall)"><input type="submit" name="submit" value="Send" class="fit special" /></div>
</div>
</form>
</div>
</section>
A much easier way to append content to a file would be to use file_put_contents():
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
file_put_contents('email.txt', $name . PHP_EOL, FILE_APPEND);
}
?>
That will create the file if it doesn't exist and append to it if it does.

Auto fill-in data (input field) from MySQL Database in PHP (PDO)

This post contains:
3 PHP pages
MySQL table picture
Picture of the form
As the title says, I need to extract some information from my database.
So far I have the following:
Index page <-- You need to login here with a personal code. (this is where I get the 'Session username' from that already works at the contact page)
Config page <-- Used for database access and all
Contact page <-- In here I would like to auto fill-in the users data.
Database table consists of:
username; email; realName (and some other stuff I don't need here)
So in the contact page I would like to see the following:
Card number = username (this already works)
Auto fill-in: realName and email according to the username.
Maybe it is possible to extract the info when logging in and storing these in the POST variable already? But how?
Database:
Table I need to use: 'members'
The info given by the user himself/herself = username
The info I need to auto fill-in = realName and email
Picture of the form.
The email should be in the SESSION statement, so I can send a confirmation email to the person, and the realName should be entered from the database.
These are the files currently running:
config.php:
<?php
ob_start();
session_start();
//set timezone
date_default_timezone_set('Europe/Brussels');
//database credentials
define('DBHOST','*****');
define('DBUSER','*****');
define('DBPASS','*****');
define('DBNAME','*****');
//application address
define('DIR','http://*****/');
define('SITEEMAIL','noreply#*****');
try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
contact form:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); }
?>
<html>
<head>
<title>*****</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/shiv.js"></script><![endif]-->
<link rel="stylesheet" href="siteassets/assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="siteassets/assets/css/ie8.css" /><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#next').keyup(calculate);
$('#nextprice').keyup(calculate);
$('#current').keyup(calculate);
$('#currentprice').keyup(calculate);
});
function calculate(e)
{
$('#total').val($('#next').val() * $('#nextprice').val() + $('#current').val() * $('#currentprice').val());
}
</script>
</head>
<body class="landing">
<div id="page-wrapper">
<!-- Header -->
<header id="header" class="alt">
<nav id="nav">
<ul>
<li>
Menu
<ul>
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
</ul>
</li>
<li>contact</li>
<li><a href='logout.php'>Logout</a></li>
</ul>
</nav>
</header>
<!-- Banner -->
<section id="banner">
<h2>*****</h2>
<p>Slogan.</p>
<ul class="actions">
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
<li>contact</li>
</ul>
</section>
<!-- Main -->
<section id="main" class="container 75%">
<div class="box">
<?
if($_SERVER['REQUEST_METHOD']=="POST")
{
if(strlen($_POST['name2']) == 0)
{ $error_msg ="- Please, provide us with your name.<br>"; }
if(!empty($error_msg))
{
//Een van de velden werd niet goed ingevuld
echo "<b>Your message can't be send due to the following reason:</b> <br><br>";
echo $error_msg;
echo "<br>Click on <a href='javascript:history.back(1)'>Go back</a> and provide us with your name.<br><br>";
}
else
{
$recipient = "*****";
$subject = "******";
$header = "From: " . $_POST['uwemail'] . "\n";
$mail_body = "Contact script werd op " . date("d-m-Y") . " om " . date("H:i") . " uur uitgevoerd.\n";
$mail_body .= "*****:\n\n";
$mail_body .= "Naam: " . $_POST['name2'] . "\n";
$mail_body .= "Met als kaartnummer: " . $_POST['card2'] . "\n";
$mail_body .= "******: " . $_POST['current2'] . "\n";
$mail_body .= "******: " . $_POST['next2'] . "\n";
$mail_body .= "Voor een totaal van: " . $_POST['total2'] . " EUR.";
$mail_body .= "\n\n -- ****** --";
mail($recipient, $subject, $mail_body, $header);
print "<b>IMPORTANT!</b>";
print "<br><br>*****.";
print "<br><br>***** ";
print $_POST['total2'];
print " *****";
print "<br><br>******.";
print "<br><br>******";
}
}
else
{
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" readonly/>
</div>
<div class="6u 12u(mobilep)">
Please enter your name. (mandatory)
<input type="text" name="name2" id="name" value="" placeholder="Your name" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Current Project - Smile
<input type="text" name="current2" id="current" value="" placeholder="How many tickets would you like?" />
</div>
<div class="6u 12u(mobilep)">
Next Project - Sand
<input type="text" name="next2" id="next" value="" placeholder="How many tickets would you like?" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice" value="10" placeholder="" />
</div>
</div>
<div class="6u 12u(mobile)">
<input name="uwemail" placeholder="Email" type="hidden" value="******"/>
</div>
<div class="6u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" readonly/>
</div>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
<?php
}
?>
</div>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© *****. All rights reserved.</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<script src="siteassets/assets/js/jquery.min.js"></script>
<script src="siteassets/assets/js/jquery.dropotron.min.js"></script>
<script src="siteassets/assets/js/jquery.scrollgress.min.js"></script>
<script src="siteassets/assets/js/skel.min.js"></script>
<script src="siteassets/assets/js/util.js"></script>
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/respond.min.js"></script><![endif]-->
<script src="siteassets/assets/js/main.js"></script>
</body>
</html>
Index page (where they have to login)
<?php
//include config
require_once('includes/config.php');
//process login form if submitted
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: home.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}//end if submit
?>
<html>
<head>
<title>******</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/iv.js"></script><! [endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /> </noscript>
</head>
<body class="is-loading">
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<section id="main">
<header>
<h1>*****</h1>
<h1><a style="color:#FFFFFF" href=''>Coming soon.</a></h1>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Login</h2>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please contact us for a new card.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Enter your card number" value=" <?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="hidden" name="password" id="password" class="form-control input-lg" value="*****" tabindex="3" >
</div>
<br>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Login" class="btn btn-primary btn-block btn-lg" tabindex="5"></div>
</div>
<hr>
<div class="row">
<div class="col-xs-9 col-sm-9 col-md-9">
<a style="color:#FFFFFF" href='*********'>Lost your card? Contact us.</a>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ******</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<!--[if lte IE 8]><script src="assets/js/respond.min.js"> </script><![endif]-->
<script>
if ('addEventListener' in window) {
window.addEventListener('load', function() { document.body.className = document.body.className.replace(/\bis-loading\b/, ''); });
document.body.className += (navigator.userAgent.match(/(MSIE|rv:11\.0)/) ? ' is-ie' : '');
}
</script>
</body>
</html>
EDITED: Since you're having user class (ex.: $user->is_logged_in()), then in $_POST[] method ignore $_POST['name2'] as it can still be changed through DEV tools and instead change that to $_SESSION['username'] (assuming that's the correct value). This is much more reliable than using HTML field. The PHP part (of query) also differs because you're using PDO, but I can't help with this one because I'm using mysqli_, not PDO (sorry about that), but query itself should be similar.
"SELECT * FROM `table` WHERE `number` = '".$_POST['number']."'"
But don't forget to escape your string, otherwise, your query is vulnerable.
I fixed the problem.
In the user.php file I had everything prepared already, but I just didn't understand why it didn't work.
Turned out to be a simple error XD
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['realName'] = $row['realName'];
$_SESSION['email'] = $row['email'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
return true;
}
}
}
?>
I forgot to add the realName and email to this line: (idiot me :D)
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');

PHP session is working on localhost but not on actual server

i'm having trouble to pass session variable to another page. It is working on localhost but not on server. I would want to pass $_SESSION['user_check'] to editpasswordsignup.php but whenever i click submit, $_SESSION['user_check'] is empty.
This is loginsignup.php
<?php
include('db.php');
session_start();
?>
<div id="wrapper">
<div id="wrapper-bg">
<div id="wrapper-bgtop">
<div class="container" id="header">
<div class="container" id="logo">
<h1></h1>
</div>
</div>
<div class="container" id="page">
<div id="loginbox">
<form action="" class="formbox" method="post">
<label>Email Address:</label>
<input class="box1" name="email" type="text">
<label>Password:</label>
<input class="box2" name="password" type="password">
<a class="myButton1" href="forgetpassword.php">Forgot Password</a><br>
<input class="submit5" name="submit" type="submit" value="Login">
Create Account
</form>
<?php
if (isset($_POST['submit']))
{
$email = ($_POST["email"]);
$password =($_POST["password"]);
$_SESSION['user_check'] = $_POST["email"];
$sql = mysql_query ("SELECT * FROM user WHERE email = '$email' ");
$row = mysql_fetch_array($sql);
$drawemail = $row['email'];
$drawpassword = $row['password'];
if (($drawemail == $email ) && ($drawpassword == $password ))
{
?>
<script>window.location = "../wordsignup.php";</script>;
<?php
}
else
{
echo "wrong password or username";
}
}
?>
</div>
</div>
<div class="container" id="footer-content-bg">
<div id="footer-content">
<ul>
<li class="footer1">
About us
</li>
<li>
Term and Conditions
</li>
<li>
Privacy Advertising
</li>
<li>
Policy
</li>
<li>
User Agreement
</li>
</ul><br>
<div id="copyright">
© . All Rights Reserved.
</div>
</div>
</div>
</div>
This is editpasswordsignup.php
<?php
include('db.php');
session_start();
$user_check = $_SESSION['user_check'];
?>
<div id="wrapper">
<div id="wrapper-bg">
<div id="wrapper-bgtop">
<div class="container" id="header">
<div class="container" id="logo">
<h1></h1>
</div>
</div>
<div class="container" id="page">
<div id="forgetpassword">
<div style="font-size:20px; color:#000080; font-weight:bold; border-width:1px; border-style:none; width:600px; margin:10px 0px 0px 175px;">
Edit Password
</div>
<div style="font-size:16px;border-style:none; width:560px; margin:20px 0px 10px 175px; font-weight:bold;">
Please enter your old password below and we will send you your password.
</div>
<div id="forgetpasswordbox">
<form class="forgetpassword" method="post">
Please enter your old password<br>
<input class="oldpassword" name="oldpassword" type="password"><br><br>
Please enter your new password<br>
<input class="newpassword" name="newpassword" type="password"><br><br>
Please re-enter new password<br>
<input class="confirmpassword" name="confirmpassword" type="password"><br><br>
<input name="submit" type="submit" value="Send" class="send">
</form>
</div>
</div>
</div>
<div class="container" id="footer-content-bg">
<div id="footer-content">
<ul>
<li class="footer1">
About Us
</li>
<li>
Term and Conditions
</li>
<li>
Privacy Advertising
</li>
<li>
Policy
</li>
<li>
User Agreement
</li>
</ul><br>
<div id="copyright">
© . All Rights Reserved.
</div>
</div>
</div>
</div>
</div>
</div>
<?php
if (isset($_POST['submit']))
{
$oldpassword = $_POST['oldpassword'];
$newpassword = $_POST['newpassword'];
$confirmpassword = $_POST['confirmpassword'];
$sql = mysql_query (("SELECT * FROM user WHERE email='user_check' AND password='$oldpassword' "),$conn);
$row = mysql_fetch_array($sql);
$email = $row['email'];
$selectpassword = $row['password'];
if ($oldpassword == "")
{
echo '<script language="javascript">';
echo 'alert("pls enter your oldpassword")';
echo '</script>';
exit;
}
if($newpassword=="")
{
echo '<script language="javascript">';
echo 'alert("pls enter your newpassword")';
echo '</script>';
exit;
}
if($confirmpassword=="")
{
echo '<script language="javascript">';
echo 'alert("pls enter your confrimpassword")';
echo '</script>';
exit;
}
if (($oldpassword) != ($selectpassword))
{
echo '<script language="javascript">';
echo 'alert("No user exists with this password '.$selectpassword.' ")';
echo '</script>';
exit;
}
if ($newpassword == ($confirmpassword))
{
mysql_query("UPDATE user SET password = '".$newpassword."' WHERE email='".$email."'");
$message = "Your password ".$newpassword." and click the link uploadsignup.php to upload your photo";
mail($email, "Change Password", $message);
?>
<script>
alert("Password Successfully change...!!!!\nClick OK to upload photo\nNewpassword will send to your email address");
window.location="uploadsignup.php";
</script>
<?php
}
else
{
echo '<script language="javascript">';
echo 'alert("new password does not match")';
echo '</script>';
}
}
?>
As you said it's working on localhost and not on the particular server, you might have a different settings in php.ini. Check out http://php.net/manual/en/session.configuration.php
I once had this problem for hours. My sessions worked on localhost but were not passing from page to page. The issue was the comments I had above the session starting. For some reason it didn't affect localhost but my server was just not having it.
So if there is anyone else reading this post with this issue, this is something else you can try.
There are several things that need to be corrected here:
1) Do not use styles in the page, use CSS classes and Id's rather than Styles. I have edited the question to remove these as they get in the way of the real code we're interested in.
2) Do not use MySQL, it is deprecated meaning it is no longer supported and the reason it is no longer supported is there are various flaws and security issues and I HIGHLY recommend looking into MySQLi or PDO as alternative methods of connecting to a database. Seriously.
3) Your issue is syntx - we'll start with brackets - see:
$email = ($_POST["email"]);
$password =($_POST["password"]);
Should be:
$email = $_POST['email'];
$password =$_POST['password'];
You do not need to put values in brackets when assigning variables. Also note that array values are in single quotes ' not double quotes. So:
$_SESSION['user_check'] = $_POST['email'];
Will work better, alternatively try this:
if (!empty($_POST['email'])){
$_SESSION['user_check'] = $_POST['email'];
}
else {
$_SESSION['user_check'] = "No Email value given in form";
}
to replace the above line.
4) Your HTML code is incomplete, your form has no action value in the second code block, these things are probably not critical but this code is ripe for errors due to being ambiguous.
5) At the top of editpasswordsignup.php (after session_start) put this:
var_dump($_SESSION['user_check']); and with the above code from point 3, this should give you an output.
6) Check your SQL:
$sql = mysql_query (("SELECT * FROM user WHERE email='user_check' AND password='$oldpassword' "),$conn);
Your email value is a string, not a variable. Your SQL here is also a complete mess, what is the reason for this?
replace the above with:
$sql = mysql_query("SELECT * FROM user WHERE email='$user_check' AND password='$oldpassword' LIMIT 1");
Complete all of the above and your code will work.
According to the op question and the answer needed why code is working on local host and not server the correct answer seems by Arun.
Too bad he has been down voted but that could be because he has not explained anything in his answer.
I have met this problem before.
The solution is make sure you do not have space above or below
<?php
line.
I am fairly certain that is why Arun has drawn lines to indicate your other php code should follow emediately.
I just had the same problem and I ended here. Even though I don't see there session_set_cookie_params() maybe you've typed it on db.php. Because of using LOCALHOST on session_set_cookie_params(time()+600,'/','LOCALHOST',false,true); session didn't work, so if you used session_set_cookie_params() you have to make sure you've replaced LOCALHOST with your domain
Try like this:
<?php session_start();
-----
-----
?>

Sanitize and send checkbox results in a form

I have a WordPress based website that includes a booking <form> on a 'Page Template'.
As I am unfamiliar with PHP, I'm not too sure exactly where I am going wrong.
I need to include some checkboxes for the services offered by the website in a <form> and have the following file to work with:
<?php
/*
* Template Name: Booking Page
*/
?>
<?php
// Sanitize data, or initialize if they don't exist.
$clientname = isset($_POST['ci_name']) ? esc_html(trim($_POST['ci_name'])) : '';
$email = isset($_POST['ci_email']) ? esc_html(trim($_POST['ci_email'])) : '';
$services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : ''; // My Edit
$message = isset($_POST['ci_comments']) ? sanitize_text_field(stripslashes($_POST['ci_comments'])) : '';
$errorString = '';
$emailSent = false;
if(isset($_POST['send_booking']))
{
// We are here because the form was submitted. Let's validate!
if(empty($clientname) or mb_strlen($clientname) < 2)
$errorString .= '<li><i class="fa fa-times"></i> '.__('Your name is required.', 'ci_theme').'</li>';
if(empty($email) or !is_email($email))
$errorString .= '<li><i class="fa fa-times"></i> '.__('A valid email is required.', 'ci_theme').'</li>';
// Services is optional, so, no check. // My Edit
// Message is optional, so, no check.
// Alright, lets send the email already!
if(empty($errorString))
{
$mailbody = __("Name:", 'ci_theme') . " " . $clientname . "\n";
$mailbody .= __("Email:", 'ci_theme') . " " . $email . "\n";
$mailbody .= __("Services Selected:", 'ci_theme') . " " . $services . "\n"; // My Edit
$mailbody .= __("Message:", 'ci_theme') . " " . $message . "\n";
// If you want to receive the email using the address of the sender, comment the next $emailSent = ... line
// and uncomment the one after it.
// Keep in mind the following comment from the wp_mail() function source:
/* If we don't have an email from the input headers default to wordpress#$sitename
* Some hosts will block outgoing mail from this address if it doesn't exist but
* there's no easy alternative. Defaulting to admin_email might appear to be another
* option but some hosts may refuse to relay mail from an unknown domain. See
* http://trac.wordpress.org/ticket/5007.
*/
$emailSent = wp_mail(ci_setting('booking_form_email'), get_option('blogname').' - '. __('Booking form', 'ci_theme'), $mailbody);
//$emailSent = wp_mail(ci_setting('contact_form_email'), get_option('blogname').' - '. __('Contact form', 'ci_theme'), $mailbody, 'From: "'.$clientname.'" <'.$email.'>');
}
}
?>
<?php get_header(); ?>
<main id="main">
<div class="container">
<div class="row">
<div class="col-lg-10 col-lg-offset-1">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 class="page-title"><?php the_title(); ?></h2>
<div class="row">
<div class="col-sm-8">
<article <?php post_class('entry'); ?>>
<?php if(!empty($errorString)): ?>
<ul id="formerrors">
<?php echo $errorString; ?>
</ul>
<?php endif; ?>
<?php if($emailSent===true): ?>
<p id="formsuccess"><i class="fa fa-check"></i> <?php _e('Your booking request has been sent. We will contact you as soon as possible.', 'ci_theme'); ?></p>
<?php elseif($emailSent===false and isset($_POST['send_booking']) and $errorString==''): ?>
<p id="sendfail"><?php _e('There was a problem while sending the email. Please try again later.', 'ci_theme'); ?></p>
<?php endif; ?>
<?php the_content(); ?>
<?php if( !isset($_POST['send_booking']) or (isset($_POST['send_booking']) and !empty($errorString)) ): ?>
<form class="booking" action="<?php the_permalink(); ?>" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="ci_name" id="ci_name" placeholder="<?php _e('your name', 'ci_theme'); ?>" value="<?php echo esc_attr($clientname); ?>">
</div>
<div class="col-md-6">
<input type="email" name="ci_email" id="ci_email" class="datepicker" placeholder="<?php _e('Your Email', 'ci_theme'); ?>" value="<?php echo esc_attr($email); ?>">
</div>
</div>
<!-- My Edits -->
<div class="row">
<div class="col-md-12">
<hr />
<p>Please tick any of the following services if you would like to include them in your package:</p>
</div>
<div class="col-md-6">
<p><input type="checkbox" name="services[]" <?php checked($services, 'Reiki'); ?> value="Reiki"> Reiki</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Private Personal Training'); ?> value="Private Personal Training"> Private Personal Training</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Walking'); ?> value="Walking"> Walking</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Boot Camp'); ?> value="Boot Camp"> Boot Camp</p>
</div>
<div class="col-md-6">
<p><input type="checkbox" name="services[]" <?php checked($services, 'Relaxation Massage'); ?> value="Relaxation Massage"> Relaxation Massage</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Meditation Circle'); ?> value="Meditation Circle"> Meditation Circle</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Colour Workshop'); ?> value="Colour Workshop"> Colour Workshop</p>
</div>
</div>
<!-- End My Edits -->
<div class="row">
<div class="col-md-12">
<textarea name="ci_comments" id="ci_comments" cols="30" rows="10" placeholder="<?php _e('Message', 'ci_theme'); ?>"></textarea>
<button type="submit" name="send_booking"><?php _e('Submit', 'ci_theme'); ?></button>
</div>
</div>
</form>
<?php endif; ?>
</article>
</div>
<?php endwhile; endif; ?>
<?php get_sidebar(); ?>
</div>
</div>
</div>
</div>
</main>
<?php get_footer(); ?>
In the code above, I have placed the HTML markup for the checkboxes in, and it appears something similar to this on the front-end of the website:
However, it doesn't seem to include the checkbox information in the email that is sent off. The email for this simply reads Services Selected: without the names of the services ticked:
My edits which can be found in the code above are:
Sanitize:
$services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : '';
Message to be sent:
$mailbody .= __("Services Selected:", 'ci_theme') . " " . $services . "\n";
Checkboxes:
<input type="checkbox" name="services[]" <?php checked($services, 'Relaxation Massage'); ?> value="Relaxation Massage"> Relaxation Massage
How do I implement, sanitize, send and receive the results of the checkboxes using the <form> I currently have?
Any help would be greatly appreciated,
Thanks.
You didn't store any value in your $service variable.
Just put this code
$clientname = isset($_POST['ci_name']) ? esc_html(trim($_POST['ci_name'])) : '';
$email = isset($_POST['ci_email']) ? esc_html(trim($_POST['ci_email'])) : '';
$services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : ''; // My Edit
$message = isset($_POST['ci_comments']) ? sanitize_text_field(stripslashes($_POST['ci_comments'])) : '';
$errorString = '';
$emailSent = false;
if(isset($_POST['send_booking']))
{
print_r($_POST);exit; // You can see here your post variable value in array.
}
Instead of
$services = isset($_POST['services']); // My Edit
Read more about the ternary operator: http://php.net/ma...operators.comparison.php

Contact form with math captcha

I've successfully created a contact form with php that gives the various required messages. Now I would like to add a simple random arithmetic captcha (non-image). See the anonymised (working) html form and existing (working, but without arithmetic captcha) php below.
The idea is to show "Incorrect answer" in the same way as the other error messages, or to pass to the Thankyou page for a correctly filled out form with correct answer. I've had a good go at this but can't quite get it to work. Any assistance much appreciated.
HTML:
<p>Area of interest:
<input type="radio" name="likeit" value="A" checked="checked" /> A
<input type="radio" name="likeit" value="B" /> B
<input type="radio" name="likeit" value="C" /> C</p>
<p>How did you hear about us?
<select name="how">
<option value=""> -- Please select -- </option>
<option>Recommendation</option>
<option>Internet</option>
<option>Advertisement</option>
<option>Other</option>
</select></p>
<p><strong>Your message subject:</strong><br /><input type="text" name="subject" size="35"/></p>
<p><strong>Your message:</strong><br />
<textarea name="comments" rows="10" cols="40"></textarea></p>
<p>Please answer the following arithmetic question: What is <?php echo $digit1;?> + <?php echo $digit2;?>?
<input name="captcha" type="text" size="2" id="captcha"/></p>
<p><input type="submit" value="Send" /></p>
</form>
PHP:
<?php
/* Contact form with arithmetic captcha */
$myemail = "enquiries#X.co.uk";
/* Check all form inputs using check_input function */
$yourname = check_input($_POST['yourname'], "Enter your name");
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$website = check_input($_POST['website']);
$likeit = check_input($_POST['likeit']);
$how_find = check_input($_POST['how']);
$subject = check_input($_POST['subject'], "Add a subject");
$comments = check_input($_POST['comments'], "Add your message");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email address is not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}
/* Message for the email */
$message = "Hello!
Your contact form has been submitted by:
Name: $yourname
Email: $email
Telephone: $telephone
URL: $website
Area of interest? $likeit
How did they find us? $how_find
Comments:
$comments
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thankyou page */
header('Location: thankyou.html');
exit();
/* Functions used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Head data in here
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="mainheader">
<div id="mainlogo">
<h1><a href="http://www.X.co.uk/" title="X">
<img style="border:0;width: 260px; height: 160px;" src="images/X.jpg" alt="X" /></a></h1>
</div>
</div>
<div id="content">
<div class="content">
<h2 class="title">Error!</h2>
<p><strong>Please correct the following error:</strong></p>
<p><?php echo $myError; ?></p>
</div>
</div>
<div id="panel">
<div id="main" class="boxed">
<h2 class="heading">Main</h2>
<ul>
<li>Home </li>
<li>About </li>
<li>Contact </li>
</ul>
</div>
<div id="services" class="boxed">
<h2 class="heading">Services</h2>
<ul>
<li>Services </li>
<li>Recent projects </li>
</ul>
</div>
<div id="pricing" class="boxed">
<h2 class="heading">Pricing</h2>
<ul>
<li>Pricing </li>
</ul>
</div>
<div id="info" class="boxed">
<h2 class="heading">Info</h2>
<ul>
<li>Tips and tricks </li>
<li>Useful links </li>
<li>Frequently asked questions </li>
<li>Site map </li>
</ul>
</div>
<div id="contact" class="boxed">
<h2 class="heading">Contact</h2>
<ul>
<li>Contact by email </li>
<li><strong>Telephone:<br />X</strong> </li>
</ul>
</div>
</div>
<div id="mainfooter">
<p> &#169; 2011 X<br />Designed by <strong>X</strong> </p>
<a href="http://validator.w3.org/check?uri=referer" title="Valid XHTML 1.0">
<img style="border:0;width:88px;height:31px" src="images/valid-xhtml10.png" alt="Valid XHTML 1.0" />
</a>
<a href="http://jigsaw.w3.org/css-validator/check/referer" title="Valid CSS!">
<img style="border:0;width:88px;height:31px" src="images/vcss.gif" alt="Valid CSS!" />
</a>
</div>
</body>
</html>
<?php
exit();
}
?>
Generally, the idea of captcha is to prevent automated form processing. Any non-image comparisons will be easily solved.
Regardless, I would use sessions to solve this issue.
Simply store the expected result in a session variable on the first page, and make sure it matches on the second
page1.php:
<?php
session_start();
$digit1 = mt_rand(1,20);
$digit2 = mt_rand(1,20);
if( mt_rand(0,1) === 1 ) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
?>
<form method="POST" action="page2.php">
What's <?php echo $math; ?> = <input name="answer" type="text" /><br />
<input type="submit" />
</form>
page2.php
session_start();
echo "You entered ".htmlentities($_POST['answer'])." which is ";
if ($_SESSION['answer'] == $_POST['answer'] )
echo 'correct';
else
echo 'wrong. We expected '.$_SESSION['answer'];
?>
Use a Simple PHP Math Captcha
https://github.com/kmlpandey77/MathCaptcha
MathCaptcha
A Simple PHP Math Captcha
Usage
composer require kmlpandey77/math-captcha
Math in Image
It will return Math in image
Create captcha.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
$captcha = new Captcha();
$captcha->image();
Create form.php
<form action="check.php" method="post">
<p>
Answer it <img src="./captcha.php" alt="" valign="middle"> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Math in Text
It will return Math in text
Create form.php
Place this code to top of form.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
?>
And place this code in body
<form action="check.php" method="post">
<p>
Answer it <?php echo new Captcha; ?> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Check
Checks to see if the user entered the correct captcha key
Create check.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
if(isset($_POST['submit'])){
if(Captcha::check()){
//valid action
echo('<font color="green">Answer is valid</font>');
}else{
echo('<font color="red">Answer is invalid</font>');
}
}

Categories