Forgot Password Recovery in Login System with PHP and MYSQL | PHP Login System

In this tutorial, we will see how to add a forgot password/reset password/recovery password in the login page using PHP and MYSQL. In the previous post we saw How to Add Remember Me Functionality in the Login Page using PHP, if you haven't read this post yet, please read that post first, after that, we will move on.

So let's start without any delay. Before we begin, let's learn a little about it and how the forgot password function work?

How does the Forgot Password System work?

There is no significant concept in this tutorial to understand. Forgot Password means that the password you created when registering is not remembered, now you have to fetch the problem in login. To overcome this problem, we will use forgot password functionality on the login page.

This code will allow us to create a new password for the users through the registered email of the users.

Ok fine, now let's start 👇

How To Add Forgot Password System in PHP

you will know that in the previous tutorial, we made a responsive registration and login form with the help of Bootstrap with the database

First of all, with the help of the last tutorial, create the registration and login form, after that, we will proceed because, without the registration and login page, we cannot add the forget password function.

If you have created a registration and login system then it does not matter and if you have not created then first you have to create a registration and login system then you have to add this forget password functionality.

See, you will also need a database here, we learned to make all this in the last tutorial.

After creating both files open login.php and search for this code.

<div class="col-6" align="right">
  <a href="recover_email.php">Forgot Password</a>
</div>

If this code is not found, enter this code on the login page and install the recover_email.php link in the anchor tag.

Create a recover_email.php file & add this code.

<?php 
include ("config.php");
include ("logic.php");
?>
<!doctype html>
  <html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <!-- Sweet Alert CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <title>Forgot Password | Rkonline</title>
  </head>
  <body>
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Logo</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
          <ul class="navbar-nav ms-auto mb-2 mb-lg-0">            
            <li class="nav-item">
              <a class="nav-link btn btn-success me-2" href="register.php">Register</a>
            </li>
            <li class="nav-item">
              <a class="nav-link btn btn-primary me-2" href="login.php">Log in</a>
            </li>    
          </ul>
        </div>
      </div>
    </nav>
     <div class="container-fluid" style="margin-top: 100px;">
  <div class="row justify-content-center">
    <div class="col-lg-4">
      <div class="card bg-info text-white">
        <h2 class="card-title text-light mt-3" align="center">Password Reset</h2>
        <p class="card-text" align="center"> Forgotten your password? Enter your email address below to send reset password email.</p>
        <hr class=" border position-relative " style="width: 70%; align-self: center; margin: 0px;">
        <div class="card-body">
          <form class="row mt-0 needs-validation" action="recover_email.php" method="post" novalidate>
            <label for="enteremail" class="form-label">Email Address</label>
              <div class="input-group has-validation">                
                <input type="email" class="form-control rounded-pill" placeholder="Enter Registered Email Address" name="email" id="enteremail" aria-describedby="inputGroupPrepend" required>
                <div class="invalid-feedback">
                  Please Enter Valid Email.
                </div>
              </div>
            <div class="col-md-12 text-center mt-3">
              <button class="btn btn-warning" title="Submit Your Form" aria-label="Left Align" name="send_reset_link" type="submit"> <span class="fa fa-paper-plane" aria-hidden="true"></span> Send Reset Link</button>
            </div>           
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="js/custom.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
<!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
-->
</body>
</html>

After adding this code. Let's write a logic to search emails from the database and if the email is not found (user not registered) then redirect users to the register.php page, and if the email is found (user registered) then we will send a mail to an email And when the user clicks on the link then he will be redirected to a new page reset_pass.php where user can change his password or create a new password.

Forgot the password code in PHP send an email

Open or create a logic.php: file & add this code.

/*------------------------------------
// Forgot Password Functionality
------------------------------------*/

if (isset($_POST['send_reset_link'])) {				
	$email = mysqli_real_escape_string($conn, $_POST['email']);
	$email_query = "SELECT * FROM users WHERE email='$email'";
	$query = mysqli_query($conn, $email_query);
	$email_count = mysqli_num_rows($query);
	if ($email_count) {
		$user_data = mysqli_fetch_array($query);
		$username = $user_data['username'];
		$token = $user_data['token'];
	$subject = " Reset Password";
	$body = "Hi, $email. Click here to Reset your Password http://localhost/regiter-form/reset_pass.php?token=$token";
	$sender_email = "From: rkonlinedotin@gmail.com"; 
	if (mail($email, $subject, $body, $sender_email)) {
		echo '<script type="text/javascript">';
    	echo 'setTimeout(function () { swal("success !","Check your email to reset your password","success");';
    	echo '}, 100);</script>';
		// header('Refresh:4; login.php');
	
	} else {
		echo '<script type="text/javascript">';
    	echo 'setTimeout(function () { swal("error!","Email Sending Failed","error");';
    	echo '}, 100);</script>';
	}

	}else{
		
		echo '<script type="text/javascript">';
	    echo 'setTimeout(function () { swal("error!","Email not found","error");';
	    echo '}, 100);</script>';
	}
}

Here we have determined in which row of the database the password will be set with the help of the token variable, where the value of the token variable will be equal, will set the password on the same row.

In the previous article, we created a database that has to create a token field in that database. So let's create a token field with the help of this command of SQL or you can also do this work manually.

SQL Command to create a token field:

ALTER TABLE `users` ADD `token` VARCHAR(100) NOT NULL AFTER `zip`;

If we look carefully at logic.php above, we have sent a link to the user and have linked a PHP file named reset_pass on that link, let's create this file, in this page, we have used only one form so that the user can create or change a new password.

create reset_pass.php: file and add this code

<?php 
include ("config.php");
include ("logic.php");
?>
<!doctype html>
  <html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <!-- Sweet Alert CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <title>Forgot Password | Rkonline</title>
  </head>
  <body>
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Logo</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
          <ul class="navbar-nav ms-auto mb-2 mb-lg-0">            
            <li class="nav-item">
              <a class="nav-link btn btn-success me-2" href="register.php">Register</a>
            </li>
            <li class="nav-item">
              <a class="nav-link btn btn-primary me-2" href="login.php">Log in</a>
            </li>    
          </ul>
        </div>
      </div>
    </nav>
    <div class="container-fluid mt-2">
  <div class="row justify-content-center">
    <div class="col-lg-4">
      <div class="card bg-info text-light">
        <h2 class="card-title text-light mt-2" align="center">Create New Password</h2>
        <p class="card-text mx-3" align="center"> Forgotten your password? Please create new perfect strong password.</p>
        <hr class=" border position-relative " style="width: 70%; align-self: center; margin: 0px;">
        <div class="card-body">
          <form class="row g-3 needs-validation" action="" method="POST" novalidate>
            <label for="validationPassword">Create Password</label>
              <input type="password" class="form-control rounded-pill" id="validationPassword" minlength="8" name="newpassword" placeholder="Password" value="" required>
              <label for="validationPassword">Confirm Password</label>
              <input type="password" class="form-control rounded-pill" id="validationPassword2" minlength="8" name="cpassword" placeholder="Password" value="" required>                     
              <div class="col-md-12 text-center ">
              <button class="btn btn-warning" title="Save Your Password" aria-label="Left Align" name="change_pass" type="submit"> <span class="fa fa-undo" aria-hidden="true"></span> Save Change</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="js/custom.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
<!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
-->
</body>
</html>

Here again, to open the logic.php file and add this code.

/*------------------------------------
	// Forgot Password, recieved token and updae password (reste_pass.php)
------------------------------------*/

if (isset($_POST['change_pass'])) {
	// fetch token from email click
if (isset($_GET['token'])) {
	// store token in a variable
	$token = $_GET['token'];
	// fetch value from form 
	$newpassword = mysqli_real_escape_string($conn, $_POST['newpassword']);
	$conf_pass = mysqli_real_escape_string($conn, $_POST['cpassword']);
	// hash password ofter submiting form
  $pass = password_hash($newpassword, PASSWORD_BCRYPT);
  $cpass = password_hash($conf_pass, PASSWORD_BCRYPT);

  if ($newpassword === $conf_pass) {
  	$update_query = "UPDATE users SET password = '$pass' WHERE token='$token' ";
  	$run_query = mysqli_query($conn, $update_query);

  	if ($run_query) {
	 echo '<script type="text/javascript">';
 	 echo 'setTimeout(function () { swal("Passsword Updated Successsfully!"," you will redirect login Page","success");';
 	 echo '}, 100);</script>';
	 header('Refresh:4; login.php');
  	}

  }else{
  	echo '<script type="text/javascript">';
    echo 'setTimeout(function () { swal("Warning!","Passsword are not matching","warning");';
    echo '}, 100);</script>';
  }

}else{
   echo '<script type="text/javascript">';
   echo 'setTimeout(function () { swal("Warning!","Passsword are not matching","warning");';
   echo '}, 100);</script>';
	}
 }
?>

In logic.php we have written this logic that if the user successfully sends an email and clicks on that link then we will allow the user to create a new password.

Maybe you will know that in the link we have passed a variable named $token with the file which will work in which row of email the user will set the password. It will set the password by fetching the value of the token field of the row from which the email is sent.

Here we have used sweet alerts CDN to show the message which shows a very beautiful message. If you want, you can use the session variable to display the message.

After creating all the files and adding the code to those files go to the URL localhost\regiter-form\login.php and click forgot Password link then check all functions work properly.

Now our forget password function is completed. I hope you found this article very useful. If there is any issue related to this article then please ask us in the comment box.

Conclusions

In this article, we have seen how forgotten password recovery is done with the help of PHP and MYSQL and how it works. If you liked this article, then please do leave a comment so that we can know that this article has been useful for you.

For such interesting PHP articles, you can follow our blogger page so that whenever we enter an article related to PHP, its notification reaches you first.

Forgot Password Recovery (Reset) using PHP and MySQL Download Source Code👇

Source Code Forgot Password Functionality Download Source Code

Post a Comment

0 Comments