Forgot Password Recovery (Reset) using PHP and MySQL

Today i will explain how to reset your account password using PHPMailer, PHP and MySQL, in this tutorial i will implement Forgot Password Recovery (Reset) using PHP and MySQL. Before moving towards the reset your password first we need a user registration and login script in php, so if you do not know how to register user and login, you can check out my tutorial about Simple User Registration & Login Script in PHP and MySQL.

To implement forgot password recovery, i will suggest you all to download and set up user registration script so that you can add forgot password functionality in it. However, it is not mandatory if you are an advance user and you can integrate it in your project then you do not need to set it up.

In my user registration tutorial there is a table name

users

, we will use the same table to check is user exist or not. You will add files of this tutorial in user registration and login script folder.

We will send an email using PHPMailer, if you do not know how to user PHPMailer so you can check my PHPMailer tutorial, i have wrote a detailed tutorial about how to send email in PHP using PHPMailer.

Steps to Forgot Password Recovery (Reset) using PHP and MySQL

We have to follow these steps to implement forgot password functionality.

  1. Create a Temporary Token Table
  2. Create a Database Connection
  3. Create an Index File (Send Email)
  4. Create a Reset Password File
  5. Create a CSS File

Let me give you a quick review of it, first we will create a table to store a token valid for one day for any user. We will also create a form that will take input of email, then we will check either email exist or not, if email is found a temporary token will be generated and email will be sent to the user with the generated token.

Once user clicked on the email token link within one day, user can reset new password. For that purpose we will also create another form that will take input of new password and update it in user table and we will also remove the temporary token from temporary token table once user successfully updated password.

1. Create a Temporary Token Table

We need to create temporary token table, run the following query.

CREATE TABLE `password_reset_temp` ( `email` varchar(250) NOT NULL, `key` varchar(250) NOT NULL, `expDate` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I have also attached sql file of this table in the download file of this tutorial.

2. Create a Database Connection

Create a database connection file with name

db.php

and add the following script in it, don’t forget to change your database credentials in this file.

$con = mysqli_connect("localhost","root","","register"); if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); die(); } date_default_timezone_set('Asia/Karachi');
$error="";

We have also define the date timezone, you can set it as per your location. This helps to store data in the timezone of your location.

3. Create an Index File (Send Email)

Now create an

index.php

file that will take email input and send an email to the user if user is found in the

users

table.

users

table is available in the login and registration script, we are using the same table.

Add the following script in

index.php

file.

<?php
include('db.php');
if(isset($_POST["email"]) && (!empty($_POST["email"]))){
$email = $_POST["email"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email) { $error .="<p>Invalid email address please type a valid email address!</p>"; }else{ $sel_query = "SELECT * FROM `users` WHERE email='".$email."'"; $results = mysqli_query($con,$sel_query); $row = mysqli_num_rows($results); if ($row==""){ $error .= "<p>No user is registered with this email address!</p>"; } } if($error!=""){ echo "<div class='error'>".$error."</div> <br /><a href='javascript:history.go(-1)'>Go Back</a>"; }else{ $expFormat = mktime( date("H"), date("i"), date("s"), date("m") ,date("d")+1, date("Y") ); $expDate = date("Y-m-d H:i:s",$expFormat); $key = md5(2418*2+$email); $addKey = substr(md5(uniqid(rand(),1)),3,10); $key = $key . $addKey;
// Insert Temp Table
mysqli_query($con, "INSERT INTO `password_reset_temp` (`email`, `key`, `expDate`)
VALUES ('".$email."', '".$key."', '".$expDate."');"); $output='<p>Dear user,</p>';
$output.='<p>Please click on the following link to reset your password.</p>';
$output.='<p>-------------------------------------------------------------</p>';
$output.='<p><a href="https://www.tutcod.com/forgot-password/reset-password.php?
key='.$key.'&email='.$email.'&action=reset" target="_blank">
https://www.tutcod.com/forgot-password/reset-password.php
?key='.$key.'&email='.$email.'&action=reset</a></p>'; $output.='<p>-------------------------------------------------------------</p>';
$output.='<p>Please be sure to copy the entire link into your browser.
The link will expire after 1 day for security reason.</p>';
$output.='<p>If you did not request this forgotten password email, no action is needed, your password will not be reset. However, you may want to log into your account and change your security password as someone may have guessed it.</p>'; $output.='<p>Thanks,</p>';
$output.='<p>tutcodTeam</p>';
$body = $output; $subject = "Password Recovery - tutcod.com"; $email_to = $email;
$fromserver = "[email protected]"; require("PHPMailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "mail.yourwebsite.com"; // Enter your host here
$mail->SMTPAuth = true;
$mail->Username = "[email protected]"; // Enter your email here
$mail->Password = "password"; //Enter your password here
$mail->Port = 25;
$mail->IsHTML(true);
$mail->From = "[email protected]";
$mail->FromName = "tutcod";
$mail->Sender = $fromserver; // indicates ReturnPath header
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($email_to);
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}else{
echo "<div class='error'>
<p>An email has been sent to you with instructions on how to reset your password.</p>
</div><br /><br /><br />"; } }
}else{
?>
<form method="post" action="" name="reset"><br /><br />
<label><strong>Enter Your Email Address:</strong></label><br /><br />
<input type="email" name="email" placeholder="[email protected]" />
<br /><br />
<input type="submit" value="Reset Password"/>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<?php } ?>

This file is simply checking if email is available in database then generate a random token, save that token in temporary table and send an email to the user with link. Once user click on the link user will be able to set new password.

4. Create a Reset Password File

Now create a rest password file, this will check that is token available in database against the user email and it should be less then one day old, once token expired user will need to regenerate token.

So if token is found user can simply set new password, we will update user password and also delete the token from temporary token table.

Insert the following script in

reset-password.php

file.

<?php
include('db.php');
if (isset($_GET["key"]) && isset($_GET["email"]) && isset($_GET["action"]) && ($_GET["action"]=="reset") && !isset($_POST["action"])){ $key = $_GET["key"]; $email = $_GET["email"]; $curDate = date("Y-m-d H:i:s"); $query = mysqli_query($con, "SELECT * FROM `password_reset_temp` WHERE `key`='".$key."' and `email`='".$email."';" ); $row = mysqli_num_rows($query); if ($row==""){ $error .= '<h2>Invalid Link</h2>
<p>The link is invalid/expired. Either you did not copy the correct link
from the email, or you have already used the key in which case it is deactivated.</p>
<p><a href="https://www.tutcod.com/forgot-password/index.php">
Click here</a> to reset password.</p>'; }else{ $row = mysqli_fetch_assoc($query); $expDate = $row['expDate']; if ($expDate >= $curDate){ ?> <br /> <form method="post" action="" name="update"> <input type="hidden" name="action" value="update" /> <br /><br /> <label><strong>Enter New Password:</strong></label><br /> <input type="password" name="pass1" maxlength="15" required /> <br /><br /> <label><strong>Re-Enter New Password:</strong></label><br /> <input type="password" name="pass2" maxlength="15" required/> <br /><br /> <input type="hidden" name="email" value="<?php echo $email;?>"/> <input type="submit" value="Reset Password" /> </form>
<?php
}else{
$error .= "<h2>Link Expired</h2>
<p>The link is expired. You are trying to use the expired link which as valid only 24 hours (1 days after request).<br /><br /></p>"; } }
if($error!=""){ echo "<div class='error'>".$error."</div><br />"; } } // isset email key validate end if(isset($_POST["email"]) && isset($_POST["action"]) && ($_POST["action"]=="update")){
$error="";
$pass1 = mysqli_real_escape_string($con,$_POST["pass1"]);
$pass2 = mysqli_real_escape_string($con,$_POST["pass2"]);
$email = $_POST["email"];
$curDate = date("Y-m-d H:i:s");
if ($pass1!=$pass2){
$error.= "<p>Password do not match, both password should be same.<br /><br /></p>"; } if($error!=""){
echo "<div class='error'>".$error."</div><br />";
}else{
$pass1 = md5($pass1);
mysqli_query($con, "UPDATE `users` SET `password`='".$pass1."', `trn_date`='".$curDate."' WHERE `email`='".$email."';"
); mysqli_query($con,"DELETE FROM `password_reset_temp` WHERE `email`='".$email."';"); echo '<div class="error"><p>Congratulations! Your password has been updated successfully.</p>
<p><a href="https://www.allphptricks.com/forgot-password/login.php">
Click here</a> to Login.</p></div><br />'; } }
?>

5. Create a CSS File

Create a file with name

style.css

and keep it in folder css. Paste the following code in it.

.error p { color:#FF0000; font-size:20px; font-weight:bold; margin:50px; }

Download

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook and share it.

Related Posts