How to make Password Reset System using Php?

Here in this tutorial blog, I will guide you How you can make a password reset system using PhpMailer, MySQL, Bootstrap 5, and HTML. Or you may be wondering how you can create a password reset system in PHP.

The first thing you have to do is to create a list of files in your server folder.

  • index.html
  • change_password.php
  • change_password_process.php
  • forgot_password.html
  • forgot_password_process.php
  • success.html

index.html

<!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">
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
    <div class="container p-3 border border-5 rounded-3" style="width: 35%;">
        <h1 class="display-6 text-center p-2 bg-light">User Login</h1>
        <form>
            <div class="row mb-3 justify-content-md-center">
                <label for="inputEmail" class="col-3 col-form-label">Email</label>
                <div class="col-lg-auto">
                    <input type="email" id="inputEmail" class="form-control">
                </div>
            </div>
            <div class="row mb-3 justify-content-md-center">
                <label for="inputPassword" class="col-3 col-form-label">Password</label>
                <div class="col-lg-auto">
                    <input type="password" name="" id="inputPassword" class="form-control">
                </div>
            </div>
            <div class="row md-3 justify-content-md-center">
                <div class="col-5">
                    <button class="btn btn-primary">SIgn in</button>
                </div>
                <div class="col-auto">
                    <a href="forgot_password.html">Forgot Password?</a>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

Line 8 – Here we are using Bootstrap 5 CDN to style our project. But if you want to use other versions of Bootstrap then you may need to modify the code accordingly.

Line 13 – We are not giving any property to the form tag because right now our focus is to create a password reset system only so this is just a demo login form which is not used for login purpose but it contains Forgot Password link.

Line 31 – When a user clicks the Forgot Password link, they will redirect to the forgot_password.html page from where they were able to set a new password.

How to make Password Reset System using Php?
Login Page – Output of index.php

forgot_password.html

<!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">
    <title>Forgot Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
    <div class="container p-3 border border-5 rounded-3" style="width: 35%;">
        <h1 class="display-6 text-center p-2 bg-light">Password Reset</h1>
        <form action="forgot_password_process.php" method="post">
            <div class="row mb-3 justify-content-md-center">
                <div class="col-auto">
                    <input type="email" name="email" placeholder="Email address" class="form-control">
                </div>
                <div class="col-auto">
                    <button type="submit" class="btn btn-primary" name="reset">Reset</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

Whenever a user clicks the forgot password link, they will redirect to this page and they have to enter their email address which they have been used for registration. Then after they click the Reset button, their email will be sent to the forgot_password_process.php page with a post method.

How to make Password Reset System using Php?
Password Reset Page – forgot_password.html

Creating a database table

CREATE TABLE `user_account` (
  `user_id` int(11) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(20) NOT NULL,
  `code` varchar(10) NOT NULL,
  `updated_time` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now use the above SQL code to create a database table under your selected database. In this table user_account, user_id, email, password columns are self-explanatory.

The code column is used to store the temporary code that was generated from the forgot_password_process.php page. You will get a further explanation in the forgot_password_process.php section.

The updated_time column is used to store the time when a password change request is summited. This time will be used to ensure that the user reset the password within a day.

Enter some dummy data.

PHPMailer

Now create a folder called mail inside the folder in which you are working right now. Then create the following files

  • Exception.php
  • OAuth.php
  • PHPMailer.php
  • POP3.php
  • SMTP.php

and copy the respective code from github.

forgot_password_process.php

<?php
    if(isset($_POST['reset'])) {
        $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';
    
    // Instantiation and passing `true` enables exceptions
    $mail = new PHPMailer(true);
    
    try {
        //Server settings
        $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@gmail.com';                     // SMTP username
        $mail->Password   = 'secret';                               // SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
    
        //Recipients
        $mail->setFrom('your_email@gmail.com', 'Admin');
        $mail->addAddress($email);     // Add a recipient

        $code = substr(str_shuffle('1234567890QWERTYUIOPASDFGHJKLZXCVBNM'),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/login_system/change_password.php?code='.$code.'">here </a>. </br>Reset your password in a day.';

        $conn = new mySqli('localhost', 'root', '', 'database_username');

        if($conn->connect_error) {
            die('Could not connect to the database.');
        }

        $verifyQuery = $conn->query("SELECT * FROM user_account WHERE email = '$email'");

        if($verifyQuery->num_rows) {
            $codeQuery = $conn->query("UPDATE user_account SET code = '$code' WHERE email = '$email'");
                
            $mail->send();
            echo 'Message has been sent, check your email';
        }
        $conn->close();
    
    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }    
?>

Line 2 – If the user directly visit the this page without pressing the reset button from forgot_password.html then this program will exit. If not, execution of code will continue.

Line 9 to11 – Include the PHPMailer library.

Line 13 to 15 – Include the PHPMailer files.

Line 18 – Creating a new mail object.

Line 23 – This is your SMTP server host name.

Line 25, 26 – This is your SMTP username and password. If you want to use your Gmail account here then use your Gmail address and password.

Line 38 – Generating a random code.

Line 41 – Create a database connection

Line 47 – Check whether the user with a given email exit in our the database or not.

Line 50 – If user exit, update the code and send the code via mail.

change_password.php

<?php include 'change_password_process.php' ?>

<!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">
    <title>Change Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
    <div class="container p-3 border border-5 rounded-3" style="width: 40%">
        <h1 class="display-6 text-center p-2 bg-light">
            Change Password
        </h1>
        <form action="" method="post">
            <div class="row mb-3 justify-content-md-center">
                <label for="inputEmail" class="col-4 col-form-label">Email</label>
                <div class="col-lg-auto">
                    <input type="email" name="email" id="inputEmail" class="form-control" required>
                </div>
            </div>
            <div class="row mb-3 justify-content-md-center">
                <label for="inputPassword" class="col-4 col-form-label">New Password</label>
                <div class="col-lg-auto">
                    <input type="password" name="new_password" id="inputPassword" class="form-control" required>
                </div>
            </div>
            <div class="row mb-3 justify-content-md-center">
                <div class="col-8">
                    <button type="submit" class="btn btn-primary" name="change">Change</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

After users request a password reset, they will get a reset link in their email address. And when they click, this type of output they will receive.

How to make Password Reset System using Php?
Change Password – Output of change_password.php

Line 1 – Here we include change_password_process.php page because it contain the code that will check whether the code is valid or not. If the code is not valid, we redirect to the login page.

If the code is valid, they can enter their email with a new password and request for change.

change_password_process.php

<?php
    if(isset($_GET['code'])) {
        $code = $_GET['code'];

        $conn = new mySqli('localhost', 'root', '', 'database_name');
        if($conn->connect_error) {
            die('Could not connect to the database');
        }

        $verifyQuery = $conn->query("SELECT * FROM user_account WHERE code = '$code' and updated_time >= NOW() - Interval 1 DAY");

        if($verifyQuery->num_rows == 0) {
            header("Location: index.html");
            exit();
        }

        if(isset($_POST['change'])) {
            $email = $_POST['email'];
            $new_password = $_POST['new_password'];

            $changeQuery = $conn->query("UPDATE user_account SET password = '$new_password' WHERE email = '$email' and code = '$code' and updated_time >= NOW() - INTERVAL 1 DAY");

            if($changeQuery) {
                header("Location: success.html");
            }
        }
        $conn->close();
    }
    else {
        header("Location: index.html");
        exit();
    }
?>

Line 2, 3 – When user click the reset link from email, they will redirect to change_password.php page indirectly to this page also. At the same time the code is received by server using Get method, if the ‘code’ set then it will jump to the next step. If not it will redirect to login page.

Line 10 – It will search for this code in the database and also check that code is created within a day. If it is false, redirect to login page.

Line 21 – If not, update with a new password and redirect to success.html page.

success.html

<!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">
    <title>Success</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
    <div class="m-3 p-3 bg-light bg-gradient text-center rounded-3">Password is sucessfully change, login <a href="index.html">here</a></div>
</body>
</html>
How to make Password Reset System using Php?
Success message

Conclusion

This is how you make a password reset system in php using PHPMailer, MySQL, Bootstrap 5, HTML.

Get the explanation on YouTube.

You may also like.

4 2 votes
Article Rating
Subscribe
Notify of
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
1 year ago

[…] Password Reset System In Php – Easy Steps – 2021 […]