Forgot Password Recovery in PHP and MySQL Login system

It is important to have a forgot password system with login panel .
Using this any user can reset his/her password without any difficulties .
reset_password_php
In this PHP tutorial ,we will be creating forgot password system.

Our previous tutorial of PHP Registration and login panel have a good startup for builing a user authentication system.Now we will ad option there
for Password reset .If you haven’t created login system with PHP, I recommend you to first visit our PHP login form tutorials.

Database Table Creation

We should have a user table inside our database to store user details Now just add a new field ‘forgot_pass_identity’ in this table .
ALTER TABLE `users` ADD `forgot_pass_identity` VARCHAR(32) NOT NULL AFTER `contact`;

Complete users table SQL will like the following.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `contact` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
 `forgot_pass_identity` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 

Forgot password form

First create a form to ask user to reset there password .

<form action="" method="post">
<p>Your Email: <input type="text" name="email"  >
<input type="submit" name="submit" value="Get New Password"></p>
</form>

Now Let’s process the submitted form .

Below we are checking if user has submitted a valid email and also if it exists in our ‘user’ table

<?php 
if(isset($_POST['submit'])){
// check for valid email address
$email = $_POST['email'];

if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
     $error[] = 'Please enter a valid email address';
}

// checks if the username is in use

$check = $mysqli->query("SELECT email FROM users WHERE email = '$email'");
$check2 = $check->num_rows;

//if the name exists it gives an error
if ($check2 == 0) {
$error[] = 'Sorry, Your emails doesn't exists in our record;
}

// if no errors

if (!$error) {
Now have to fetch username from the table and create an object .
To create a new password we randomly generate one using substr, md5, uniqid and rand function which generate a random password 10 characters long, 
then on the next line we convert it to a encrypted password using md5 which will be inserted into the database after the new password has been email to the user.

$query = $mysqli->query("SELECT username FROM users WHERE email = '$email' ");
$r=$mysqli->fetch_object($query);
 
//create a new random password

$password = substr(md5(uniqid(rand(),1)),3,10);
$pass = md5($password); //encrypted version for database entry

Below create message to send to user’s email .Mention your own domain’s email address instead of contact@domain.com and noprely@domain.com

//send email
$to = "$email";
$subject = "Password Recovery";
$body = "Hi $r->username, nn 
you or someone else have requested your account details. nn 
Here is your account information please keep this as you may need this at a later stage. nn
Your username is $r->username nn your password is $password nn 
Your password has been reset please login and change your password .nn 
Regards Your Website";

$lheaders= "From: <contact@domain.com>rn";
$lheaders.= "Reply-To: noprely@domain.com";

mail($to, $subject, $body, $additionalheaders);

So, we have successfully sent password to user’s email. Now time to update encrypted password of the user record . Then set a variable to true we will use this to determine if the reset has been successful.

//update database
$sql = $mysqli->query("UPDATE users SET password='$pass' WHERE email = '$email'");
$rsent = true;

}
}


Below show any errors if there any.

<pre>
if (!empty($error))
{
        $i = 0;
        while ($i < count($error)){
        echo "<div class='error-msg'>".$error[$i]."</div>";
        $i ++;}
}// close if empty errors

Finally checking if the reset was successful if so, show a message there.

if ($rsent == true){
    echo "<p>Just sent an email with your account details to $email</p>n";
    } else {
    echo "<p>Please enter your e-mail address. You will receive a new password via e-mail.</p>n";
    }

Here's the full script:

<?php
//This code runs if the form has been submitted
if (isset($_POST['submit']))
{

// check for valid email address
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
     $error[] = 'Please enter a valid email address';
}

// checks if the username is in use
$check = $mysqli->query("SELECT email FROM users WHERE email = '$email'");
$check2 =$check->num_rows;

 
//if the name exists it gives an error
if ($check2 == 0) {
$error[] = 'Sorry, Your emails doesn't exists in our record;
}

 
if (!$error) {

$query = $mysqli->query("SELECT username FROM users WHERE email = '$email' ");
$r=$mysqli->fetch_object($query);

//create a new random password

$password = substr(md5(uniqid(rand(),1)),3,10);
$pass = md5($password); //encrypted version for database entry

//send email
$to = "$email";
$subject = "Account Details Recovery";
$body = "Hi $r->username, nn you or someone else have requested your account details. nn Here is your account information please keep this as you may need this at a later stage. nnYour username is $r->username nn your password is $password nn Your password has been reset please login and change your password to something more rememberable.nn Regards Site Admin";
$lheaders= "From: <contact@domain.com>rn";
$lheaders.= "Reply-To: noprely@domain.com";
mail($to, $subject, $body, $additionalheaders);

//update database
$sql = $mysqli->query("UPDATE users SET password='$pass' WHERE email = '$email'");
$rsent = true;


}// close errors
}// close if form sent

//show any errors
if (!empty($error))
{
        $i = 0;
        while ($i < count($error)){
        echo "<div class='error-msg'>".$error[$i]."</div>";
        $i ++;}
}// close if empty errors


if ($rsent == true){
    echo "<p>Just sent an email with your account details to $email</p>n";
    } else {
    echo "<p>Please enter your e-mail address. You will receive a new password via e-mail.</p>n";
    }

?>

<form action="" method="post">
<p>Your Email: <input type="text" name="email" size="50" maxlength="255">
<input type="submit" name="submit" value="Get New Password"></p>
</form>

  • Sidra Emaan

    its not working

Online Web Development Training,Video Tutorials