With the help of this tutorial, we will show how to reset your account password using PHPMailer, PHP and MySQL
In this tutorial, I will implement password recovery (reset) using PHP and MySQL. Before proceeding to reset your password first, we need user registration and login script in PHP. After doing that, we have first to implement a password forgot recovery. We will suggest you all download and set up a user registration script so that you can add a ‘forgot password’ feature in it. But, it is not necessary if you are an advanced user, and you can integrate it into your project, then there is no need to set it up.
In this user registration tutorial, there are table name users. We will use the same table to check the user exists or not. You will add files of this tutorial in user registration and login script folder. So we will send an email using PHPMailer
Steps to Forgot Password Recovery (Reset) using PHP and MySQL
Follow these steps to implement a ‘forgot password’ functionality.
- Create a Temporary Token Table
- Make a Database Connection
- Create an Index File (Send Email)
- Make a Reset Password File
- Create a CSS File
Let me first do a quick review of this, and we will create a table for any user to store valid tokens for one day. We will also create a form that will take input from the email after That we will check either email exist or not. If the email is found, a temporary token will be generated, and email will be sent to the user with the generated token.
Once the user clicked on the email token link within one day, the user can reset a new password.
For this, we will also create another form that will take input of a new password and update it in the user table. We will also delete the temporary token from a temporary token table after the user successfully updates the password.
1. Create a Temporary Token Table
We need to create a 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;
2. Make a Database ConnectionI have also attached the SQL file of this table to the download file of this blog.
Make a database connection file with name db.php after that add the following script in it, and 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 defined the date timezone, and you can set it as per your location. It helps to store data in the timezone of your site.
3. Create an Index File (Send Email)
Create an index.php file that will take email input and send the email when the user is found in the user’s table. The user table is available in the login and registration script. We are using the same table. Add the following script to the 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.allsWeb.com/forgot-password/reset-password.php? key='.$key.'&email='.$email.'&action=reset" target="_blank"> https://www.allsWeb.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>allsWeb Team</p>'; $body = $output; $subject = "Password Recovery - allsWeb.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 = "allsWeb"; $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> </p> <p> </p> <p> </p> <?php } ?>
This file is merely checking if the email is available in the database, then generate a random token, save that token in a temporary table, and send an email to the user with a link. Once the user clicks on the link user will be able to set a new password.
4. Make a Reset Password File
Now create a rest password file. It will check that it is token available in a database against the user email, and it should be less than one day old. Once token expired user will need to regenerate token.
So if the token is found user can set a new password. We will update the user password and also delete the symbol from a temporary token table.
Insert the following script in a 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.allsWeb.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.allsWeb.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; }
If you found this tutorial helpful, share it with your friends and developers group.
Also, read our previous blog- Create and Consume Simple REST API in PHP