Create Forgot Password and Reset Password Functionality Using PHP.

Here, we are going to write a program to create forgot password and reset password functionality using PHP in XAMPP software. We will be using PHPmailer to send the reset password link in the mail to the user. We will also be updating the new password in the database. We will have two files, Recover_email.php file and Reset_password.php file.

Recover-email.php

<?php
$sname= "localhost";
$unmae= "root";
$password = "";
$db_name = "vsitdatabase";
$conn = mysqli_connect($sname, $unmae, $password, $db_name); ?>

if (!$conn) {
    echo "Connection failed!";
    exit;
}
<!DOCTYPE html>
<html lang="en"> 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.css"  type="text/css">
    <link rel="stylesheet" href="css/style.css"  type="text/css">
    <title>Document</title>
</head>
<style>
.shade{
    box-shadow: rgb(38, 57, 77) 0px 20px 30px -10px;
 }
</style>
<body>
<section class=" text-center text-lg-start d-flex justify-content-center">
<div class="card shade mb-3 ms-5 me-5 w-75 bg-light" style="margin-top:100px;">
        <article class="card-body mx-auto" style="max-width:400px;">
         <h4 class="card-title mt-3 text-center"> Recover Password</h4>
         <p class="text-center"> Please enter your email address</p>

         <form action="recover_email.php" method="POST">
            <div class="form-group input-group">
                <input name="email" class="form-control" placeholder="Email Address" type="email" required>
            </div>
            <div class="form-group">
                <button type="submit" name="submit" class="btn btn-primary btn-block mt-3 px-5 mx-5"> Send Email</button>
            </div>
         </form>
        </article>
    </div>
</section>
<script src="javascript/bootstrap.js" type="text/javascript"></script>
<script src="javascript/jquery-3.6.3.min.js" type="text/javascript"></script> 
<?php 
if(isset($_POST['submit'])){
    $email = $_POST['email'];
}else{
    exit();
}
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'mail/Exception.php';
require 'mail/PHPMailer.php';
require 'mail/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings                     //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'your email address';                     //SMTP username
    $mail->Password   = 'app password';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;            //Enable implicit TLS encryption
    $mail->Port       = 587;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('your email id ', 'Admin');
    $mail->addAddress($email);     //Add a recipient

    $code=substr(str_shuffle('0123456789QWERTYUIOPASDFGHJKLZXCVBNM'),0,10);
    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Password Reset';
    $mail->Body    = 'To reset your password click <a href="http://localhost/vsitWebsite/vsitAdmin/reset_password.php?code='.$code.'">here.</a>Reset your password in a day.';
     
    $verifyquery=mysqli_query($conn,"SELECT * from login where email='$email'");
    $usercount=mysqli_num_rows($verifyquery);
    if($usercount===1){
   $codequery=mysqli_query($conn,"UPDATE login set Token='$code' where email='$email'");
   $mail->send();
    header('Location:index.php?success=Message has been sent, check your email');
    }
    
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
ob_flush();
?>
</body>
</html>

Reset_password.php file

<?
session_start();
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.css"  type="text/css">
    <title>Document</title>
    <style>
.shade{
    box-shadow: rgb(38, 57, 77) 0px 20px 30px -10px;
 }
</style>
</head>
<body>
<?php 
$sname= "localhost";
$unmae= "root";
$password = "";
$db_name = "vsitdatabase";
$conn = mysqli_connect($sname, $unmae, $password, $db_name);

if (!$conn) {
    echo "Connection failed!";
    exit;
}


 if(isset($_POST['change'])){
    if(isset($_GET['code'])){
    $code=$_GET['code'];
      $newpass=mysqli_real_escape_string($conn,$_POST['npass']);
      $cnfrmpass=mysqli_real_escape_string($conn,$_POST['cpass']);

      $newpass=md5($newpass);
      $cnfrmpass=md5($cnfrmpass);

      if($newpass==$cnfrmpass){
        $updatequery="update login set password='$newpass' where Token='$code'";
        $iquery=mysqli_query($conn,$updatequery);
        if($iquery){
            header("Location:index.php?success=password has been updated");
        }else{
            $_SESSION['errmsg'] = "your password is not updated";
            header("Location:reset_password.php");
        }
      }else{
        $_SESSION['errmsg'] = "password does not match";
      }
    }else{
        echo "No user found";
    }
 }
?>
<section class=" text-center text-lg-start d-flex justify-content-center">
<div class="card shade mb-3 ms-5 me-5 w-75 bg-light" style="margin-top:100px;">
        <article class="card-body mx-auto" style="max-width:400px;">
         <h4 class="card-title mt-3 text-center"> Change Password</h4>
         <p class="text-center"> Please fill the following details.</p>
         <p class="bg-info text-white px-5"><?php
         if(isset($_SESSION['errmsg'])){
            echo $_SESSION['errmsg']; 
         }
         else{
            echo $_SESSION['errmsg'] = "";
         }
         ?></p>
         <form action="" method="POST">
            <div class="form-group input-group">
                <input name="npass" class="form-control" placeholder="New Password" type="password" required>
            </div>
            <div class="form-group input-group">
                <input name="cpass" class="form-control mt-3" placeholder="Confirm Password" type="password" required>
            </div>
            <div class="form-group">
                <button type="submit" name="change" class="btn btn-primary btn-block mt-3 ps-5 pe-5">Change Password</button>
            </div>
         </form>
        </article>
</div>
</section>
<script src="javascript/bootstrap.js" type="text/javascript"></script>
<script src="javascript/jquery-3.6.3.min.js" type="text/javascript"></script> 
</body>
</html>