Please note, this is a STATIC archive of website technosmarter.com from July 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
 

Forgot Password and password reset form in PHP with MYSQL


Every time most of the peoples forget their password and try to reset the password on the website.

We are creating registration and login form in PHP from the scratch. In this tutorial, we will create a forgot password form and reset the password form in PHP with MYSQL.

In the previous tutorial, we had create a registration and login system in PHP also we created a forgot password link on the login page.

In this tutorial, we will create a forgot password system in PHP

Forgot Password form in PHP with MYSQL –

The forgot password form is used to update the user password using the link on the email.

In the forgot password form, the user enters a username or email to find his account and click on the send link button. The password reset link goes to the user email and the user clicks on the link. The user redirects to the password reset page and updates his password.

In this forgot password system, we will create two forms. First for find out the user and second for a password reset.

Create a database table –

In the previous tutorial, we had create a user table and now will create a password reset table.


CREATE TABLE `pass_reset` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL,
  `token` varchar(255) NOT NULL, 
   PRIMARY KEY (`id`)
);

Execute the query above in your PHPMYADMIN panel.

In this table above, we have created two fields. We will insert an email and token in the password reset table after finding the account. We will send a password reset link with a password reset form page and token.

The token will be a random id. We will find an email with token and update by email id. This is really easy.

Create a forgot password form -

In the previous tutorial, we used bootstrap to design responsive forms also we had create an extra CSS file in the Previous tutorial.

Let's create a forgot password form –

Create a file with the name – forgot-password.php

forgot-password.php


<!DOCTYPE html>
<?php require_once("config.php");
if(isset($_SESSION["login_sess"])) 
{
  header("location:account.php"); 
}
?>
<html>
<head>
<title> Forgot Password - Techno Smarter</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> 
<link rel="stylesheet" href="style.css">
</head>
<body>

Have an account? Login

Don't have an account? Sign up

</body> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </html>

In the code above, we have created one field to find out the user account.

Forgot password form in PHP and MYSQL

Now, we will create a forgot password process file.

Create PHP scripts for forgot password form –

In this PHP file, we will follow the steps –

  1. Find the user account with the entered value. If the user account exits or not in our system database.
  2. If the user found then fetch the email and insert it into the pass_reset data table with token id.

The token id will be generated with and random_bytes() PHP function .


$token = bin2hex(random_bytes(50));
  1. Insert email and token id pass_reset table.
  2. Now, we will use the PHP mail() function to send an email on the user email id
  3. In the message of mail()function, we will send some text with password reset form and token id link.

$msg="Your password reset link 
https://technosmarter.com/php/form/password-reset.php?token=".$token."
Reset your password with this link .Click or open in new tab



".$credits."
";

The user will receive the link to the password reset form page and click on it.

Create a file with the name –   forgot_process.php

forgot_process.php


<?php 
 require_once("config.php");
if(isset($_POST['subforgot'])){ 
$login=$_REQUEST['login_var'];
$query = "select * from  users where (username='$login' OR email = '$login')"; 
$res = mysqli_query($dbc,$query);
$result=mysqli_fetch_array($res);
if($result)
{
$findresult = mysqli_query($dbc, "SELECT * FROM users WHERE (username='$login' OR email = '$login')");
if($res = mysqli_fetch_array($findresult))
{
$oldftemail = $res['email'];  
}
$token = bin2hex(random_bytes(50));
 $inresult = mysqli_query($dbc,"insert into pass_reset values('','$oldftemail','$token')"); 
 if ($inresult)  
 { 
$FromName="Techno Smarter";
$FromEmail="[email protected]";
$ReplyTo="[email protected]";
$credits="All rights are reserved | Techno Smarter "; 
$headers  = "MIME-Version: 1.0\n";
     $headers .= "Content-type: text/html; charset=iso-8859-1\n";
     $headers .= "From: ".$FromName." <".$FromEmail.">\n";
      $headers .= "Reply-To: ".$ReplyTo."\n";
      $headers .= "X-Sender: <".$FromEmail.">\n";
       $headers .= "X-Mailer: PHP\n"; 
       $headers .= "X-Priority: 1\n"; 
       $headers .= "Return-Path: <".$FromEmail.">\n"; 
         $subject="You have received password reset email"; 
     $msg="Your password reset link <br> https://localhost:8081/php/form/password-reset.php?token=".$token." <br> Reset your password with this link .Click or open in new tab<br><br> <br> <br> <center>".$credits."</center>"; 
   if(@mail($oldftemail, $subject, $msg, $headers,'-f'.$FromEmail) ){
header("location:forgot-password.php?sent=1"); 
$hide='1';
          
    } else {
        
    header("location:forgot-password.php?servererr=1"); 
} 
      } 
      else 
      { 
          header("location:forgot-password.php?something_wrong=1"); 
      }     
}
else  
{
header("location:forgot-password.php?err=".$login); 
}
}
?>

You can understand the code by the points above.

Let’s create a password reset form –

Password reset form in PHP with MYSQL –

The password reset form comes after clicking on the link. It’s used to update passwords. This is another form like the registration form. We remove all other fields and only leave the password and confirm the password in the form.

We get the value of the token and find the email that relates to the token. If the email has found then we will use that email to reset the password in the user's table. The remaining process will be the same as the update operation in PHP . Convert password simple text to hash pattern and update using an update query.

Create a file with the name – password-reset.php

password-reset.php


<!DOCTYPE html>
<?php require_once("config.php");
if(isset($_SESSION["login_sess"])) 
{
  header("location:account.php"); 
}
?>
<html>
<head>
<title> Password Reset - Techno Smarter</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> 
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php if(isset($_GET['token'])) { $token= $_GET['token']; } //form for submit if(isset($_POST['sub_set'])){ extract($_POST); if($password ==''){ $error[] = 'Please enter the password.'; } if($passwordConfirm ==''){ $error[] = 'Please confirm the password.'; } if($password != $passwordConfirm){ $error[] = 'Passwords do not match.'; } if(strlen($password)<5){ // min $error[] = 'The password is 6 characters long.'; } if(strlen($password)>50){ // Max $error[] = 'Password: Max length 50 Characters Not allowed'; } $fetchresultok = mysqli_query($dbc, "SELECT email FROM pass_reset WHERE token='$token'"); if($res = mysqli_fetch_array($fetchresultok)) { $email= $res['email']; } if(isset($email) != '' ) { $emailtok=$email; } else { $error[] = 'Link has been expired or something missing '; $hide=1; } if(!isset($error)){ $options = array("cost"=>4); $password = password_hash($password,PASSWORD_BCRYPT,$options); $resultresetpass= mysqli_query($dbc, "UPDATE users SET password='$password' WHERE email='$emailtok'"); if($resultresetpass) { $success="<div class='successmsg'><span style='font-size:100px;'>&#9989;</span>
Your password has been updated successfully..
<a href='login.php' style='color:#fff;'>Login here... </a> </div>"; $resultdel = mysqli_query($dbc, "DELETE FROM pass_reset WHERE token='$token'"); $hide=1; } } } ?>
</body> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </html>
Password reset form in PHP

In the PHP code above, you can see, we used the delete operation after updated password. This is really important that we delete tokens from the pass_reset table after updating the password.

In this way, you can create a forgotten password system or you can say forgot password form link for login form in PHP website.


Please Share

Recommended Posts:-