How to fix this PHP Forgotten Password Script? - php

So basically, I'm trying to make a simple, yet secure, forgotten password script.
There are two scripts, one that allows the user to enter their email address. This will then send them an email with a link that they must visit to save their new password.
The second script is where the link leads to. This script saves the new password.
For security purposes, I made a new table within my database called 'token'. It has three fields; token, email, used. Token is a random generated string of 10 letters and numbers, email is just that users email address, and used is an integer of either 1 or 0 indicating whether or not the token has been used.
You will be able to understand far more of my structure once you read over the two scripts. They are not to long, and not complex at all.
What is going wrong
Okay, so there is only one small thing going wrong, and this is within the reset-password.php script. This is where the users come to after they receive the email. Basically, I type in a new password, and click 'Reset Password', yet nothing happens. No errors or confirmations are shown, along with nothing changing within my database. I can't seem to debug this, and have been searching and trying for hours now. All help and suggestions would be greatly appreciated.
Please try to keep in mind that I am still a newbie at PHP and MySQL. Been working with PHP for approximately 8 weeks now, and MySQL for only 2.
forgot-password.php
<?php
//Forgotten password script
//Variable to save errors
$errors = array();
$email = $_POST['email'];
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$query = "SELECT email FROM users WHERE email='" . $email . "'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num==0)
{
echo ("<div style='color:red;'>Email address is not registered</div>");
die();
}
$token = getRandomString(10);
$query = "INSERT INTO tokens (token,email) VALUES ('".$token."','".$email."')";
mysql_query($query);
//function to renerate the token
function getRandomString($length)
{
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++)
{
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
//Send the reset link to the user
function mailresetlink($to,$token)
{
$subject = "Password Reset";
$message = '
<html>
<head>
<title>Password Reset</title>
</head>
<body>
<p>Click on the given link to reset your password Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Password Reset <noreply#domain.com>' . "\r\n";
if(mail($to,$subject,$message,$headers))
{
echo "We have sent the password reset link to your email at <strong>".$to."</strong>";
}
}
//If email is posted, send the email
if(isset($_POST['email']))
{
mailresetlink($email,$token);
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>Email Address: </td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Reset My Password" /></td></tr>
<input type="hidden" name="register" value="TRUE" />
</form>
</table>
reset-password.php
<?php
//Reset password script
$token = $_GET['token'];
$email;
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(!isset($_POST['newpassword']))
{
$query = "SELECT email FROM tokens WHERE token='" . $token . "' AND used = 0";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$email = $row['email'];
}
if ($email != '')
{
$_SESSION['email'] = $email;
}
else
{
echo "Invalid link or Password already changed";
}
}
$pass = $_POST['newpassword'];
$email = $_SESSION['email'];
//Save new password
if(isset($_POST['newpassword']) && isset($_SESSION['email']))
{
$query = "UPDATE users SET password = SHA('$password') WHERE email='" . $email . "'";
$result = mysql_query($query);
if($result)
{
mysql_query("UPDATE tokens SET used=1 WHERE token='" . $token . "'");
}
echo "Your password has been changed successfully";
if(!$result)
{
echo "An error occurred. Please try the again or contact us at admin#domain.com";
}
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
Please, if you need any more information or code, please do not hesitate to ask.
Thanks in advance!

I don't see anywhere where you are passing the token parameter to the server on the reset page after entering the new password parameter. You should have another hidden <input /> control, I would expect. $_SERVER['PHP_SELF'] does not return query string parameters. That is likely the cause of your current problem.
Specifically,
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
should be
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
<input type="hidden" name="token" value="<?php echo $_REQUEST['token']; ?>" />
</form>
</table>
Make sure you also change any $_GET['token']s to $_REQUEST['token'] as it will be GET the first time, then POST the second.
That being said, your much larger problem is the ability for me to bypass all your security by specifying ' or 1=1 or ' as my token. Or, I could be mean and do a nice '; update users set password = SHA('IKnowThisPassword') where username = 'admin'; --
Moral of the story being parameterized SQL (How can I prevent SQL injection in PHP?)

Related

PHP Username and Password verification

I'm currently working on a class project where I have to verify the username and password against a database. I stored the values of the username and password in individual arrays and I'm trying to verify that the user input matches one of the values in there. However, that's not happening, and I'm not sure how to fix it. Thanks for your help!
<?
connectDB();
$sql = "SELECT* FROM employee";
$result = mysqli_query($db,$sql) or die ("SQL error: " . mysqli_error());
$row = mysqli_fetch_array($result);
$password = array();
$username = array();
while($row = mysqli_fetch_array($result))
{
$password[] = $row['emp_pword'];
$username[] = $row['emp_username'];
}
var_dump($password);
var_dump($username);
?>
<?php if (isset($_REQUEST['page1_submit'])) {
if (($_REQUEST['pword'] == $password) and ($_REQUEST['user'] == $username)) {
header('location:home_agent.php');
} else { ?>
<h2>Wrong Password! Try again.</h2>
<form method="POST" action="login.php">
<table class="info">
<tr>
<th>Username:</th>
<td><input type="text" NAME="username" />
</td>
<th>Password:</th>
<td><input type="password" NAME="pword" /></td>
</tr>
</table>
<input class="submit" type="submit" name="page2_submit" value="SUBMIT" />
<input class="submit" type="reset" value="RESET" />
</form>
<?php }
ME TOO THINKS YOU ARE WRONG .
YOU JUST EXECUTE QUERY
" SELECT * FROM TBLE_NAME WHERE username=$username AND password=$password"
check this query gives a non empty list for verify login
thats all.

php not updating password nor token in the d.b

My forgot password is not updating the token table nor is it updating the password when changes it keeps echoing the error message below is the form code:
Forgot Password</strong></h3>
<form name="forgot" method="POST" id="forgot" action="includes/reset.php">
<div align="center">
<table width="372" border="0">
<tr>
<td width="181"><p> </p>
<p><strong>Password</strong></p></td>
<td width="181"><span id="sprytextfield1"><br />
<label for="label"></label>
<input type="password" name="passsowrd" id="password" />
<span class="textfieldRequiredMsg">Your password is required</span></span></td>
</tr>
<tr>
<td><p> </p>
<p><strong>Confenter code hereirm Password</strong></p></td>
<td><span id="spryconfirm2">
<label for="password"></label>
<input type="password" name="password2" id="password" />
<span class="confirmRequiredMsg">A value is required.</span><span class="confirmInvalidMsg">The values don't match.</span></span></td>
</tr>
</table>
</div>
<div align="center">
<p> </p>
<table width="98" border="0">
<tr>
<th width="44" scope="row"><input type="submit" name="submit" id="submit" value="submit" /></th>
<th width="44" scope="row"><input type="reset" name="clear" id="clear" value="Clear" /></th>
</tr>
</table>
</div>
<div align="center">
<table width="372" border="0">
<tr> </tr>
<tr> </tr>
</table>
</div>
</form>
and the reset.php is:
<?php
session_start();
error_reporting(0);
$token=$_GET['token'];
include("settings.php");
connect();
if(!isset($_POST['password'])){
$q="select email from tokens where token='".$token."' and used=0";
$r=mysql_query($q);
while($row=mysql_fetch_array($r))
{
$email=$row['email'];
}
If ($email!=''){
$_SESSION['email']=$email;
}
else die("Invalid link or Password already changed <a href='../index.php'>Click here to go back to the HOME PAGE<a/>");}
$pass=$_POST['password'];
$email=$_SESSION['email'];
if(isset($_POST['password'])&&isset($_SESSION['email']))
{
$q="update registration set password='".md5($pass)."' where email='".$email."'";
$r=mysql_query($q);
if($r)mysql_query("update tokens set used=1 where token='".$token."'");echo "Your password is changed successfully <a href='../index.php'>Click here to go back to the HOME PAGE<a/>";
if(!$r)echo "An error occurred";
}
so the issue is the following error message is echoed all the time:
Invalid link or Password already changed.
what should i do also if i add:
if(!isset($pass)){
echo '<form method="post">
enter your new password:<input type="password" name="password" />
<input type="submit" value="Change Password">
</form>
';}
then it works but opens it in new blank page which is un professional thats y am trying to add it to the html
Your else die is in the totally wrong place. You are always going to die because while will always evaluate to false as the loop ends.
If your intent was to die if the query fails you should do something like:
$r = mysql_query($q);
if (false === $r) {
die(mysql_error());
}
while ($row = mysql_fetch_array($r)) {
...
}
Of course my general advice is to not use mysql functions at all, as they are deprecated with PHP 5.5. You also should make sure you are explicitly handling all the possible outcomes for you queries and log meaningful errors to help you debug.
You have no token being passed in the code you presented
$token=$_GET['token'];
where is that token coming from in the script, it is not calling it from the database,
$q="select email from tokens where token='".$token."' and used=0";
also you are not guarding against any sql injection, that should really be addressed, unless I missed the part of the code where the token was being sent to the reset page, if so my apologies
$r=mysql_query($q);
while($row=mysql_fetch_array($r))
{
$email=$row['email'];
}
If ($email!=''){
$_SESSION['email']=$email;
}
else die
flowing down your code you run the query to select email where the token would be blank, i assume no email is returned so if the email is not blank do this, or else die... it must die because the the $email is blank
You're closing your while block too soon. Move the } below the die
I was going to edit your post, but there were so many formatting and syntax issues I'll post it as an answer instead.
<?php
session_start();
error_reporting(0);
include 'settings.php';
connect();
$token = $_GET['token'];
$pass = $_POST['password'];
if (isset($pass) && isset($token)) {
$q = 'SELECT email FROM tokens WHERE token=' . $token . ' AND used=0';
$r = mysql_query($q);
while ($row = mysql_fetch_array($r)) {
$email = $row['email'];
}
if ($email != '') {
$_SESSION['email'] = $email; // Why?
$q = 'UPDATE registration SET password=' . md5($pass). ' WHERE email=' . $email;
$r = mysql_query($q);
if ($r) {
mysql_query('UPDATE tokens SET used=1 WHERE token=' . $token);
echo 'Your password is changed successfully <a href="../index.php">Click here to go back to the HOME PAGE<a/>';
} else {
echo 'An error occurred';
}
} else {
die('Invalid link or Password already changed <a href="../index.php">Click here to go back to the HOME PAGE<a/>');
}
}
This shnould get you on the right track, please take note of tabs, curly braces and most importantly, be consistent in how you write code. Stick to single or double quotes, always use curly braces even on single line if/else statements.
However, as others have said, this code is still highly insecure and deprecated, but it should work.

PHP MySQL: Why is my form loading a plaintext page?

I have tried to implement a form that changes a password in a database, however, when I submit the details on the form, it just directs me to the target page...but shows up and the plaintext code on the browser....why is it doing this!
The form:
<h1 align="center">Change Password</h1>
<form method="POST" action="reset_pwd.php">
<table class='altrowstable' id='alternatecolor' >
<tr>
<td align="right">Username: </td>
<td><input type="TEXT" name="username" value=""/></td>
</tr>
<tr>
<td align="right">Current Password: </td>
<td><input type="password" name="password" value=""/></td>
</tr>
<tr>
<td align="right">New Password: </td>
<td><input type="password" name="npassword" value=""/></td>
</tr>
<tr>
<td align="right">Repeat New Password: </td>
<td><input type="password" name="rpassword" value=""/></td>
</tr>
<tr><td align="center">
Forgot password
</td>
<td>
<input type="submit" name="submit" value="Change Password"/>
</td>
</tr>
</table>
</form>
<br>
<?php echo $msg; ?>
and the target php page:
<?php
include('dbconfig.php');
$msg = "";
if (mysql_real_escape_string($_POST['submit'])):
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$npassword = mysql_real_escape_string(md5($_POST['npassword']));
$rpassword = mysql_real_escape_string(md5($_POST['rpassword']));
$sql = "SELECT * FROM user_info WHERE user_id = '$username' ";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
while ($rows = mysql_fetch_array($query)):
$dbusername = $rows['username'];
$dbpassword = $rows['password'];
$dbfirstname = $rows ['firstname'];
$dblastname = $rows ['lastname'];
endwhile;
if (empty($username) || empty($password) || empty($npassword) ||
empty($rpassword)):
$msg = "All fields are required";
elseif ($numrows == 0):
$msg = "This username does not exist";
elseif ($password != $dbpassword):
$msg = "The CURRENT password you entered is incorrect.";
elseif ($npassword != $rpassword):
$msg = "Your new passwords do not match";
elseif ($npassword == $password):
$msg = "Your new password cannot match your old password";
else:
mysql_query("UPDATE user_info SET password = '$npassword' WHERE user_id =
'$username'");
$to = $email;
$subject = "YOUR PASSWORD HAS BEEN CHANGED";
$message = "<p>Hello $dbfirstname $dblastname. You've received this E-Mail
because you have requested a PASSWORD CHANGE. ";
$from = "myemail#.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
endif;
endif;
?>
PLease check... What is the type of "user_id" in "user_info" table... and what are you getting in user name field from your form.
am asking about this query...
$sql = "SELECT * FROM user_info WHERE user_id = '$username' ";
First $msg in target php is only for target php,won't return value back to the form
Second,you may looking for
if (isset($_POST['submit'])): instead of
if (mysql_real_escape_string($_POST['submit'])):
There is no html response from the target page to be displayed in browser. For displaying content you need to form proper html so that it can be displayed in browser.
In target page add the below html code at the end so that the message (validation or success) can be displayed.
<html><body>put your message here</body></htm>
You might have forgotten an extra ?> at the end of your included file "dbconfig.php", thus treating your target php page as html.

Converting 'eregi_replace' function to 'preg_replace' and a 'mysql_num_rows' parameter fix

I've made a register.php file to sign up for a website I'm currently building. I'm running XAMPP to host my website and test it before I upload it via a paid host. After making the php file with the help of a few video's and online forums I opened it in google chrome and filled out the registration form I had created. But upon pressing 'submit' was presented with the following errors instead of having the user info successfully written into the mysql database.
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 53
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\register.php on line 56
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 97
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 98
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 99
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 100
I know that the reason for errors related to the eregi_replace() function is because it is no longer being supported/used by the php language. I also am aware there is an alternative of preg_replace() However the problem stands that as a newbie in the field of php I am not able to come up with a solution. I'm learning a little more everyday but I need this page done quickly to continue on with my website and with school I don't have time to try out so many multiple blocks of code to come up with a solution. I apologize; I'm going to need a little spoon feeding. :/ If you can take my code and tell me how to fix the errors listed above, or even better respond with a fixed copy of the code, It would be very greatly appreciated! Thank you for your time and once again I apologize for my lack of knowledge.
register.php:
<?php
//User check log
//include_once("Scripts/checkuserlog.php");
?>
<?php
// let's initialize vars to be printed to page in the HTML section so our script does not return errors
// they must be initialized in some server environments
$errorMsg = "";
$firstname = "";
$lastname = "";
$email1 = "";
$email2 = "";
$pass1 = "";
$pass2 = "";
// This code runs only if the form submit button is pressed
if (isset ($_POST['firstname'])){
/* Example of cleaning variables in a loop
$vars = "";
foreach ($_POST as $key => $value) {
$value = stripslashes($value);
$vars .= "$key = $value<br />";
}
print "$vars";
exit();
*/
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$email1 = stripslashes($email1);
$pass1 = stripslashes($pass1);
$email2 = stripslashes($email2);
$pass2 = stripslashes($pass2);
$firstname = strip_tags($firstname);
$lastname = strip_tags($lastname);
$email1 = strip_tags($email1);
$pass1 = strip_tags($pass1);
$email2 = strip_tags($email2);
$pass2 = strip_tags($pass2);
// Connect to database
include_once "/Scripts/connect_to_mysql.php";
$emailCHecker = mysql_real_escape_string($email1);
$emailCHecker = eregi_replace("`", "", $emailCHecker);
// Database duplicate e-mail check setup for use below in the error handling if else conditionals
$sql_email_check = mysql_query("SELECT email FROM members WHERE email='$emailCHecker'");
$email_check = mysql_num_rows($sql_email_check);
// Error handling for missing data
if ((!$firstname) || (!$lastname) || (!$email1) || (!$email2) || (!$pass1) || (!$pass2)) {
$errorMsg = 'ERROR: You did not submit the following required information:<br /><br />';
if(!$firstname){
$errorMsg .= ' * First Name<br />';
}
if(!$lastname){
$errorMsg .= ' * Last Name<br />';
}
if(!$email1){
$errorMsg .= ' * Email Address<br />';
}
if(!$email2){
$errorMsg .= ' * Confirm Email Address<br />';
}
if(!$pass1){
$errorMsg .= ' * Login Password<br />';
}
if(!$pass2){
$errorMsg .= ' * Confirm Login Password<br />';
}
} else if ($email1 != $email2) {
$errorMsg = 'ERROR: Your Email fields below do not match<br />';
} else if ($pass1 != $pass2) {
$errorMsg = 'ERROR: Your Password fields below do not match<br />';
} else if ($email_check > 0) {
$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our database. Please use another.<br />";
} else { // Error handling is ended, process the data and add member to database
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email1 = mysql_real_escape_string($email1);
$pass1 = mysql_real_escape_string($pass1);
$firstname = eregi_replace("`", "", $firstname);
$lastname = eregi_replace("`", "", $lastname);
$email1 = eregi_replace("`", "", $email1);
$pass1 = eregi_replace("`", "", $pass1);
// Add MD5 Hash to the password variable
$db_password = md5($pass1);
// Add user info into the database table for the main site table(audiopeeps.com)
$sql = mysql_query("INSERT INTO members (firstname, lastname, email, password, sign_up_date)
VALUES('$firstname','$lastname','$email1','$db_password', now())")
or die (mysql_error());
$id = mysql_insert_id();
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
mkdir("members/$id", 0755);
//!!!!!!!!!!!!!!!!!!!!!!!!! Email User the activation link !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$to = "$email1";
$from = "admin#Connect.CloudNine.com";
$subject = "Complete your registration at Cloud Nine";
//Begin HTML Email Message
$message = "Hi $firstname,
Complete this step to activate your login identity at [ yourdomain ].
Click the line below to activate when ready.
localhost/activation.php?id=$id&sequence=$db_password
If the URL above is not an active link, please copy and paste it into your browser address bar
Login after successful activation using your:
E-mail Address: $email1
Password: $pass1
See you on the site!
";
//end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text\r\n";
mail($to, $subject, $message, $headers);
$msgToUser = "<h2>One Last Step - Activate through Email</h2><h4>OK $firstname, one last step to verify your email identity:</h4><br />
In a moment you will be sent an Activation link to your email address.<br /><br />
<br />
<strong><font color=\"#990000\">VERY IMPORTANT:</font></strong>
If you check your email with your host providers default email application, there may be issues with seeing the email contents. If this happens to you and you cannot read the message to activate, download the file and open using a text editor.<br /><br />
";
include_once 'msgToUser.php';
exit();
} // Close else after duplication checks
} else { // if the form is not posted with variables, place default empty variables
$errorMsg = "Fields marked with an [ * ] are required";
$firstname = "";
$lastname = "";
$email1 = "";
$email2 = "";
$pass1 = "";
$pass2 = "";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome To Cloud Nine</title>
<link href="CSS/register.css" rel="stylesheet" type="text/css">
<link href="CSS/css_boxes_register.css" rel="stylesheet" type="text/css">
<link href="CSS/reg_table_register.css" rel="stylesheet" type="text/css">
</head>
<body>
<!--Floating Dock-->
<div id="floating_dock">
<img src="Images/cloudnine_logo.png" width="220px">
<img src="Images/button.png" width="75" height="50" id="button"></div>
<!--Floating Dock End-->
<!--Content Wrap-->
<div id="container_alt">
<form action="register.php" method="post" enctype="multipart/form-data" class="box">
<h3>Account Registration</h3>
<p> </p>
<p>
<table width="447" border="0" align="center" cellpadding="5" cellspacing="1">
<tr>
<td width="435" align="center" valign="middle"><?php print "$errorMsg"; ?></td>
</tr>
<tr>
<td align="center">First Name</td>
</tr>
<tr>
<td align="center"><input name="firstname" type="text" id="firstname" value="<?php print "$firstname";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Last Name</td>
</tr>
<tr>
<td align="center"><input name="lastname" type="text" id="lastname" value="<?php print "$lastname";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Password</td>
</tr>
<tr>
<td align="center"><input name="pass1" type="text" id="pass1" value="<?php print "$pass1";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Confirm Password</td>
</tr>
<tr>
<td align="center"><input name="pass2" type="text" id="pass2" value="<?php print "$pass2";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Email</td>
</tr>
<tr>
<td align="center"><input name="email1" type="text" id="email1" value="<?php print "$email1";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Confirm Email</td>
</tr>
<tr>
<td align="center"><input name="email2" type="text" id="email2" value="<?php print "$email2";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center"><input type="submit" name="submit" value="Submit Form"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</p>
</form>
</div>
</body>
</html>
No need to do regexp if you don't need it. Change
eregi_replace("`", "", $emailCHecker);
to
str_replace("`", "", $emailCHecker);
Do not use the mysql_* functions since they are deprecated. Use mysqli or PDO or whatever flavor you like but do not use mysql_* anymore!
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL
extension should be used. See also MySQL: choosing an API guide and
related FAQ for more information.

Difficulty on retrieving email address on a register form with php and mysql

Hi im am trying to allow users to be members in a website. The code I have does not look to have any bugs or anything. When i try to register as a user it keeps show me an error that i haven't inserted the email address. The email field does exists in the database and i cannot find the problem.
PHP Script
$errorMsg = "";
// First we check to see if the form has been submitted
if (isset($_POST['username'])){
//Connect to the database through our include
include_once "connect_to_mysql.php";
// Filter the posted variables
$username = str_replace("[^A-Z a-z0-9]", "", $_POST['username']); // filter everything but numbers and letters
$country = str_replace("[^A-Z a-z0-9]", "", $_POST['country']); // filter everything but spaces, numbers, and letters
$county = str_replace("[^A-Z a-z0-9]", "", $_POST['county']); // filter everything but spaces, numbers, and letters
$city = str_replace("[^A-Z a-z0-9]", "", $_POST['city']); // filter everything but spaces, numbers, and letters
$accounttype = str_replace("[^a-z]", "", $_POST['accounttype']); // filter everything but lowercase letters
$email=str_replace( '/#/', '#', $email );
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = str_replace("[^A-Z a-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
// Check to see if the user filled all fields with
// the "Required"(*) symbol next to them in the join form
// and print out to them what they have forgotten to put in
if((!$username) || (!$country) || (!$county) || (!$city) || (!$accounttype) || (!$email) || (!$password)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$username){
$errorMsg .= "--- User Name";
} else if(!$country){
$errorMsg .= "--- Country";
} else if(!$county){
$errorMsg .= "--- State";
} else if(!$city){
$errorMsg .= "--- City";
} else if(!$accounttype){
$errorMsg .= "--- Account Type";
} else if(!$email){
$errorMsg .= "--- Email Address";
} else if(!$password){
$errorMsg .= "--- Password";
}
} else {
// Database duplicate Fields Check
$sql_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$sql_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$username_check = mysql_num_rows($sql_username_check);
$email_check = mysql_num_rows($sql_email_check);
if ($username_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside our system. Please try another.";
} else if ($email_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our system. Please try another.";
} else {
// Add MD5 Hash to the password variable
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, country, county, city, accounttype, email, password, signupdate)
VALUES('$username','$country','$state','$city','$accounttype','$email','$hashedPass', now())") or die (mysql_error());
// Get the inserted ID here to use in the activation email
$id = mysql_insert_id();
// Create directory(folder) to hold each user files(pics, MP3s, etc.)
mkdir("memberFiles/$id", 0755);
// Start assembly of Email Member the activation link
$to = "$email";
// Change this to your site admin email
$from = "info#chrysikourtina.x10.mx";
$subject = "Complete your registration";
//Begin HTML Email Message where you need to change the activation URL inside
$message = '<html>
<body bgcolor="#FFFFFF">
Hi ' . $username . ',
<br /><br />
You must complete this step to activate your account with us.
<br /><br />
Please click here to activate now >>
<a href="http://http://chrysikourtina.x10.mx/activation.php?id=' . $id . '">
ACTIVATE NOW</a>
<br /><br />
Your Login Data is as follows:
<br /><br />
E-mail Address: ' . $email . ' <br />
Password: ' . $password . '
<br /><br />
Thanks!
</body>
</html>';
// end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
$to = "$to";
// Finally send the activation email to the member
mail($to, $subject, $message, $headers);
// Then print a message to the browser for the joiner
print "<br /><br /><br /><h4>OK $firstname, one last step to verify your email identity:</h4><br />
We just sent an Activation link to: $email<br /><br />
<strong><font color=\"#990000\">Please check your email inbox in a moment</font></strong> to click on the Activation <br />
Link inside the message. After email activation you can log in.";
exit(); // Exit so the form and page does not display, just this success message
} // Close else after database duplicate field value checks
} // Close else after missing vars check
} //Close if $_POST
?>
HTML Form
<table width="600" align="center" cellpadding="4">
<tr>
<td width="7%">REGISTER AS A MEMBER HERE </td>
</tr>
</table>
<table width="600" align="center" cellpadding="5">
<form action="join_form.php" method="post" enctype="multipart/form-data">
<tr>
<td colspan="2"><font color="#FF0000"><?php echo "$errorMsg"; ?></font></td>
</tr>
<tr>
<td width="163"><div align="right">User Name:</div></td>
<td width="409"><input name="username" type="text" value="<?php echo "$username"; ?>" /></td>
</tr>
<tr>
<td><div align="right">Country:</div></td>
<td><select name="country">
<option value="<?php echo "$country"; ?>"><?php echo "$country"; ?></option>
<option value="Cyprus">Cyprus</option>
<option value="United Kingdom">United Kingdom</option>
</select></td>
</tr>
<tr>
<td><div align="right">County: </div></td>
<td><input name="county" type="text" value="<?php echo "$county"; ?>" /></td>
</tr>
<tr>
<td><div align="right">City: </div></td>
<td>
<input name="city" type="text" value="<?php echo "$city"; ?>" />
</td>
</tr>
<tr>
<td><div align="right">Account Type: </div></td>
<td><select name="accounttype">
<option value="<?php echo "$accounttype"; ?>"><?php echo "$accounttype"; ?></option>
<option value="a">Normal User</option>
<option value="b">Expert User</option>
<option value="c">Super User</option>
</select></td>
</tr>
<tr>
<td><div align="right">Email: </div></td>
<td><input name="email" type="text" id="<?php echo "$email"; ?>" value="<?php echo "$email"; ?>" />
</td>
</tr>
<tr>
<td><div align="right"> Password: </div></td>
<td><input name="password" type="password" value="<?php echo "$password"; ?>" />
<font size="-2" color="#006600">(letters or numbers only, no spaces no symbols)</font></td>
</tr>
<tr>
<td><div align="right"> Captcha: </div></td>
<td>Add Captcha Here for security</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input type="submit" name="Submit" value="Submit Form" /></td>
</tr>
</form>
</table>
Error : You did not submit the following required information!
--- Email Address
All the other fields seem to be working fine!! If anyone has any idea of what is causing the problem please tell me!! Thanks
EDIT: IF you still get the same result the problem is with mysql_real_escape_string
because it's the only function which return FALSE.
You forgot to define the value of the email variable.
add this:
$email = $_POST['email'];
above this:
$email=str_replace( '/#/', '#', $email );
and add this below:
$email = mysql_real_escape_string(strip_tags(stripslashes($email)));
I believe you need to first get post value, then play with it. So consider the order change as below:
$email = stripslashes($_POST['email']);
$email=str_replace( '/#/', '#', $email );
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
Also a check in html file may work for further errors.
<?php $email = isset($_POST['email']) ? $_POST['email'] : ''; ?>
Hope this works.
Use echo to display your variable's values. See what $mail is when it is posted but before any filters are applied, and after each filter is applied. This can narrow down your search to where the error is actually occurring.

Categories