Dj Techblog

A blog on web development

Reset forgot password in php

Last Modified on on July 18, 2021
Generating One time url for email verification

Reset forgot password is an important tool for every website with login-logout system. Not having a reset forgot password tool might create problem for the users as well as admin. Because, in absence of it user will lost control to his/her account.

Forgot password is a mechanism to help user regain control over his lost account. So, to help user come out of such situation web developer employs some techniques so that user can reset his password and login again to lost account.

I will explain here how to generate one time url to reset forgot password in php.

Follow these steps.

  1. Create two tables to store user data
  2. Get Email id to send password reset link.
  3. Identify the account generate token and send the password reset link.
  4. Delete the token when user follows the one time password reset link.
  5. Update the password.

Create two tables to store user data

We need two table one temporary table forgot-password-request and another permanent table registered-user. Temporary table will store the request that are coming from users to reset their forgot password. It will have three columns name, email, and a unique token. Token will be generated on the basis of user email and stored in the temporary database. The token will be valid for 24 hours only. And once user uses the temporary password reset link, the token will be automatically deleted.

Permanent table registered-user has two columns email and password which will be updated.

    CREATE TABLE forgot-password-request ( name TEXT NOT NULL , email TEXT NOT NULL , token TEXT NOT NULL , PRIMARY KEY (token(40)));
                
    CREATE TABLE registered-user ( name TEXT NOT NULL , email TEXT NOT NULL , password TEXT NOT NULL , PRIMARY KEY (email(40)));
                

Get Email id to send one time password reset url

The user enters his email id to receive the one time password reset link. A script has been written to check for invalid email id which returns an error on entering an invalid email id.

Landing page : index.html

<!DOCTYPE html>
<html>
<head>
<title>Forgot password in php</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
	<div class="container">
		<div class="err"></div>
		<form id="mobile-number-verification">
			<div class="mobile-heading">Forgot password</div>
			<div class="mobile-row">
				<input type="email" id="email" class="mobile-input" placeholder="Enter your email-id">
				<div id="message2"></div>
			</div>
			<div id="loading-image"><img src="/image/ajax-loader.gif" alt="ajax loader"></div>
			<input type="button" class="mobileSubmit" id="enter" disabled="true" value="Send password reset link" onClick="generateUrl();">
		</form>
	</div>
			<script>
		    $('#email').on('keyup',function(){
  		            var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  		            var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  		            var email = $("#email").val();
  		            if(email.match(mailformat)){
  		                $('#message2').html('valid').css('color','green');
  		                $("#enter").prop('disabled',false);
  		            }
  		            else
  		                $('#message2').html('Invalid Email').css('color','red');
  		                
  		        }
  		        );
		</script>
	</body>
</html>
        

Javascript code makes an ajax request to the server

The javascript function makes an ajax request and send email-id to server.

script.js

        function generateUrl() {
          $(".err").html("").hide();
          var email = $("#email").val();
          var name = $("#name").val();	
          if(name.length !== 0)
          {
              var input ={
                  "name" : name,
                  "email" : email,
                  "action" : "generate_url"
              }
              $("#loading-image").show();
              $.ajax({
                  
                  url : 'controller.php',
                  type : 'POST',
                  dataType : 'json',
                  data : input,
                  success : function(response)
                  {
                      $(".container").html(response.message);
                  },
                  complete : function()
                  {
                      $("#loading-image").hide();
                  },
                  error : function()
                  {
                      $(".container").html("Error");
                  }
                  
              });
          }
          else
              $("#message1").html("Enter your name").css('color','red');
          
        }
        

Server forwards one time password reset link to the email-id

The server checks whether any account is associated with the given email id or not. If it finds an account, it generates a unique token, insert it into a temporary database with the email id. The generated token is then embeded into the url and send to the email id. If no account associated with the email id is found, the server returns with an error message.

controller.php

        <?php
    error_reporting(E_ALL & ~ E_NOTICE);
        switch ($_POST["action"]) {
            
            case "generate_url":
                $email = $_POST['email'];
                $name = "User";
                $token = sha1(uniqid($email,true)); // this will generate unique 40 character long secured token
                $db = mysqli_connect('localhost', 'database-username', 'password', 'database-name');
                //here check for email id ia already registered or not
                $query = "INSERT INTO forgot-password-request (name,email,token) VALUES ('$name','$email','$token')";
                
                $result = mysqli_query($db, $query);
  	            if ($result === FALSE) 
  	            {
                    die(mysqli_error());
                    exit();
  	            }
  	            else{
                        $url = "https://djtechblog.com/php/projects/forgot-password-in-php/user-verification.php?token=$token";// send this url to user via email
                        $message = "Follow this link " . $url . " to to reset forgot password.";
                        $sub = "Activate your account";
                        $headers = "MIME-Version: 1.0" . "\r\n";
                        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                        $headers .= 'From: Dj Techblog <dj@djtechblog.com>' . "\r\n";
                        $retval = mail($email,$sub,$message,$headers);
                        if($retval = true)
                            echo json_encode(array( "type" =>"success", "message" => "Password link has been sent to email id"));
                        else
                            echo json_encode(array( "type" =>"error", "message" => "Error sending mail."));
  	            }
            	break;
        }    
        
        ?>
                                    

User follows the one time password reset link


Now we assume that the user receives the one time password reset link and will follow the link to reset his password. The server retrieves the token from the url and matches it with the token stored in the temporary database. If both matches , that means the password reset request is genuine and a password reset form is presented to the user. Otherwise server discards the token as an invalid or expired token. We also delete the token when user is presented with a password reset form so that token can not be reused in any case.

user-verification.php

        <?php
        
        // retrieve token
        if (isset($_GET["token"]) && preg_match('/^[0-9A-F]{40}$/i', $_GET["token"])) {
            $token = $_GET["token"];
        }
        else {
            throw new Exception("Valid token not provided.");
                header('location: index.php');
        
        }
        
        $db = mysqli_connect('localhost', 'usrname', 'password', 'database');
        $query = "SELECT * FROM forgot-password-request WHERE token='$token' LIMIT 1";
        
        $result =  mysqli_query($db, $query);
        if ($result === FALSE) 
        {
           die(mysqli_error($connect));
        }
        $user = mysqli_fetch_assoc($result);
        if($user)
        {
           
            if ($user['token'] === $token) 
            {
                    // delete token so it can't be used again
                    $query1 = "DELETE FROM forgot-password-request WHERE token='$token' LIMIT 1";
                    $result1 =  mysqli_query($db, $query1);
                    if($result1 === TRUE){
                        // do one-time action here, like activating a user account
                        //  or delete the record from forgot-password-request and creating a new record in registered_users.
                        echo "Password Reset";
                    }
                    else
                      exit;
            }
        }
        
        ?>
        <html>
            <head>
                <link href="style.css" type="text/css" rel="stylesheet" />
            </head>
            <body>
                  <div class="container">
        
                        <form method="post" id="mobile-number-verification" action="update-password.php">
                            <div class="mobile-heading"> Reset your password </div>
                          <div class="mobile-row">
                            <input type="hidden" name="email" value="<?php echo $user['email']; ?>">
                            <input type="password" class="mobile-input" name="password1" placeholder="Enter your password">
                            <br><br>
                            <input type="password" class="mobile-input" name="password2" placeholder="Confirm your password">
                              <div id="message2"></div>
                          </div>
                          <div id="loading-image"><img src="/image/ajax-loader.gif" alt="ajax loader"></div>
                          <input type="submit" class="mobileSubmit" id="enter" name="update-password" value="Update Password">
                
                        </form>
                    </div>
            </body>
        </html>
        
password reset form in php

Reset the forgot password


User is redirected to update-password.php. We check whether both the password entered matches or not. If the password match we make a database connection and update the password in the table. We can redirect the user to the login page on successful password update.

update-password.php

        <?php
        if(isset($_POST['update-password']))
        {
                        $password1 = $_POST['password1'];
                        $password2 = $_POST['password2'];
                        $email = $_POST['email'];
        
                        if($password1 != $password2)
                        {
                            echo "password do not match";
                        }
                        $db = mysqli_connect('localhost', 'database-username', 'password', 'database-name');
                        $password = md5('$password1');
                        $query =  "UPDATE registered-user SET password='$password' where email='$email'";
                    $result1 = mysqli_query($db, $query);
                            if ($result1 === FALSE) 
                        {
                        die(mysqli_error($connect));
                       
                       }
                                else
                                {
                                        echo "password update successful";
                                        header("location: login.php");
                                }
        }
        
        ?>
        
        

Download the style.css file from here.


Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section