Reset password – PHP & MySQL

04 June, 2020

MySQL
PHP
Reset password - PHP and MySQL

We will be using 4 files to implement reset password option.

  • index.php (to get email address)
  • send-recovery-mail.php (to send email)
  • reset-password.php (to enter new password)
  • new-password.php (to update the password)

Your table structure should be like this:

You need to create a table in database called users and the most important columns are email and reset_token. Sending email via localhost requires an Gmail account and you need to enable less secure apps for your account. You can enable it from the link below:

Enable less secure apps

Enter email address

Create a simple form to get user’s email address, where recovery mail should be sent.

<form method="POST" action="send-recovery-mail.php">
    <input type="email" name="email">
    <input type="submit" value="Send recovery email">
</form>

Send recovery email

We will be using PHPMailer library, you can download it from the link below:

Download PHPMailer

Next you need to include the library and make a connection with database:

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

First you need to check if a user of that email exists in your database:

$email = $_POST["email"];

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    //
}
else
{
    echo "Email does not exists";
}

Inside the if statement, you need to generate a unique token which will be sent in email:

if (mysqli_num_rows($result) > 0)
{
    $reset_token = time() . md5($email);
}
else
{
    echo "Email does not exists";
}

After that, you need to save this token against that user’s database record:

$sql = "UPDATE users SET reset_token='$reset_token' WHERE email='$email'";
mysqli_query($connection, $sql);

Then you create a variable called $message and write all the text that you want to send in recovery email:

$message = "<p>Please click the link below to reset your password</p>";
$message .= "<a href='http://localhost/tutorials/add-a-reset-password-option/reset-password.php?email=$email&reset_token=$reset_token'>";
	$message .= "Reset password";
$message .= "</a>";
  • Replace your web URL with the highlighted text.

Now, simply send the email via PHPMailer. We have created a separate function to do that:

function send_mail($to, $subject, $message)
{
    $mail = new PHPMailer(true);

    try {
        //Server settings
	$mail->SMTPDebug = 0;                                       // Enable verbose debug output
	$mail->isSMTP();                                            // Set mailer to use SMTP
	$mail->Host       = 'smtp.gmail.com;';  // Specify main and backup SMTP servers
	$mail->SMTPAuth   = true;                                   // Enable SMTP authentication
	$mail->Username   = 'your_gmail_address';                     // SMTP username
	$mail->Password   = 'your_gmail_password';                               // SMTP password
	$mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
	$mail->Port       = 587;                                    // TCP port to connect to

	$mail->setFrom('your_gmail_address', 'your_name');
	//Recipients
	$mail->addAddress($to);

	// Content
	$mail->isHTML(true);                                  // Set email format to HTML
	$mail->Subject = $subject;
	$mail->Body    = $message;

	$mail->send();
	echo 'Message has been sent';
    } catch (Exception $e) {
	echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}

And you can call this function right after$message variable:

send_mail($email, "Reset password", $message);

At this point, when you enter email and hit submit you will receive an email with a receovery link. On clicking you will be redirected to your site on page reset-password.php.

Enter new password

Now you need to create a file named reset-password.php. In this file, first you need to check if it comes from email link:

<?php

$email = $_GET["email"];
$reset_token = $_GET["reset_token"];

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    //
}
else
{
    echo "Email does not exists";
}

Second, you need to check if the token is not tempered, so that you cannot change someone else’s password:

$user = mysqli_fetch_object($result);
if ($user->reset_token == $reset_token)
{
    //
}
else
{
    echo "Recovery email has been expired";
}

Third, display a simple form to enter new password. The email and reset_token needs to be hidden in this file so that you can update password for only that specific user:

if ($user->reset_token == $reset_token)
{
    ?>
    <form method="POST" action="new-password.php">
        <input type="hidden" name="email" value="<?php echo $email; ?>">
    	<input type="hidden" name="reset_token" value="<?php echo $reset_token; ?>">
		
    	<input type="password" name="new_password" placeholder="Enter new password">
    	<input type="submit" value="Change password">
    </form>
    <?php
}
else
{
    echo "Recovery email has been expired";
}

Reset the password

Now you only needs to create a new file named new-password.php and paste the following code in it:

<?php

$email = $_POST["email"];
$reset_token = $_POST["reset_token"];
$new_password = $_POST["new_password"];

$connection = mysqli_connect("localhost", "root", "", "classicmodels");

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
    $user = mysqli_fetch_object($result);
    if ($user->reset_token == $reset_token)
    {
    	$sql = "UPDATE users SET password='$new_password' WHERE email='$email' AND reset_token='$reset_token'";
    	mysqli_query($connection, $sql);

    	echo "Password has been changed";
    }
    else
    {
    	echo "Recovery email has been expired";
    }
}
else
{
    echo "Email does not exists";
}

That’s how you can reset password using PHP and MySQL. Learn also how you can do email verification in your website.

About Author

Adnan Afzal

Developer, technology evangalist, loves to read and write about new technologies. Madly in love with backend development. Follow him on social media.