PHP Send Reset Password Link Email

To send forgot password link on email for reset password in PHP; In this tutorial, i am going to show you how to send reset password link on email in PHP + MySQL with link expiry time. and how to send email using gmail smtp server in PHP.

Send reset password link with expiry time in php mysql tutorial, i will create forgot password form and using this form to send reset password link email with expiry time. Then create update password form and using this form update password into MySQL database + PHP.

PHP + MySQL Send Reset Password Link with Expiry time

  • Step 1 – Create PHP Project
  • Step 2 – Create Database Table And Connect App to DB
  • Step 3 – Create Forgot Password HTML Form
  • Step 4 – Send Email With Reset Link
  • Step 5 – Create Update Password Form
  • Step 6 – Update New Password into MySQL DB

Step 1 – Create PHP Project

In step 1, Navigate to your local web server directory. And inside this directory, create one directory. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 2 – Create Database Table And Connect App to DB

In step 2, you need to create database and table. So run the following sql query to create database and table:

CREATE DATABASE my_db;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(250) NOT NULL,
  `status` int(11) NOT NULL DEFAULT '0',
  `reset_link_token` varchar(255) NOT NULL,
  `exp_date` TIMESTAMP NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Then create a php file that named mydbCon. Which is used to connect phpmyadmin mysql database to project (demo).

So, now create mydbCon file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $conn= mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 3 – Create Forgot Password HTML Form

In step 3, create a php file that named index.php. This file will display PHP simple form and store form data into MySQL database with validation. Now, you need to add the following simple form code into index.php file:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
      <title>Send Reset Password Link with Expiry Time in PHP MySQL - Laratutorials.com</title>
       <!-- CSS -->
       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
   </head>
   <body>
      <div class="container">
          <div class="card">
            <div class="card-header text-center">
              Send Reset Password Link with Expiry Time in PHP MySQL - Laratutorials
            </div>
            <div class="card-body">
              <form action="password-reset-token.php" method="post">
                <div class="form-group">
                  <label for="exampleInputEmail1">Email address</label>
                  <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp">
                  <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
                </div>
                <input type="submit" name="password-reset-token" class="btn btn-primary">
              </form>
            </div>
          </div>
      </div>

   </body>
</html>

Step 4 – Send Email With Reset Link

In step 4, create one php file, which name password-reset-token.php . And add the following code into it:

<?php
if(isset($_POST['password-reset-token']) && $_POST['email'])
{
    include "mydbCon.php";
    
    $emailId = $_POST['email'];

    $result = mysqli_query($conn,"SELECT * FROM users WHERE email='" . $emailId . "'");

    $row= mysqli_fetch_array($result);

  if($row)
  {
    
     $token = md5($emailId).rand(10,9999);

     $expFormat = mktime(
     date("H"), date("i"), date("s"), date("m") ,date("d")+1, date("Y")
     );

    $expDate = date("Y-m-d H:i:s",$expFormat);

    $update = mysqli_query($conn,"UPDATE users set  password='" . $password . "', reset_link_token='" . $token . "' ,exp_date='" . $expDate . "' WHERE email='" . $emailId . "'");

    $link = "<a href='www.yourwebsite.com/reset-password.php?key=".$emailId."&token=".$token."'>Click To Reset password</a>";

    require_once('phpmail/PHPMailerAutoload.php');

    $mail = new PHPMailer();

    $mail->CharSet =  "utf-8";
    $mail->IsSMTP();
    // enable SMTP authentication
    $mail->SMTPAuth = true;                  
    // GMAIL username
    $mail->Username = "[email protected]";
    // GMAIL password
    $mail->Password = "your_gmail_password";
    $mail->SMTPSecure = "ssl";  
    // sets GMAIL as the SMTP server
    $mail->Host = "smtp.gmail.com";
    // set the SMTP port for the GMAIL server
    $mail->Port = "465";
    $mail->From='[email protected]';
    $mail->FromName='your_name';
    $mail->AddAddress('reciever_email_id', 'reciever_name');
    $mail->Subject  =  'Reset Password';
    $mail->IsHTML(true);
    $mail->Body    = 'Click On This Link to Reset Password '.$link.'';
    if($mail->Send())
    {
      echo "Check Your Email and Click on the link sent to your email";
    }
    else
    {
      echo "Mail Error - >".$mail->ErrorInfo;
    }
  }else{
    echo "Invalid Email Address. Go back";
  }
}
?>

The password-reset-token.php file code will store reset password link with expiry time into MySQL database and send email to reset password link in PHP + MySQL.

Note that:- And Add the smtp details in password-reset-token.php file.

Step 5 – Create Update Password Form

In step 5, create one php file, which name reset-password.php . And add the following code into it:

<!doctype html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
      <title>Reset Password In PHP MySQL</title>
       <!-- CSS -->
       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
   </head>
   <body>

      <div class="container">
          <div class="card">
            <div class="card-header text-center">
              Reset Password In PHP MySQL
            </div>
            <div class="card-body">
          <?php
            if($_GET['key'] && $_GET['token'])
            {
              include "mydbCon.php";
              
              $email = $_GET['key'];

              $token = $_GET['token'];

              $query = mysqli_query($conn,
              "SELECT * FROM `users` WHERE `reset_link_token`='".$token."' and `email`='".$email."';"
              );

              $curDate = date("Y-m-d H:i:s");


              if (mysqli_num_rows($query) > 0) {

               $row= mysqli_fetch_array($query);

              if($row['exp_date'] >= $curDate){ ?>
              <form action="update-forget-password.php" method="post">
                <input type="hidden" name="email" value="<?php echo $email;?>">
                <input type="hidden" name="reset_link_token" value="<?php echo $token;?>">
                <div class="form-group">
                  <label for="exampleInputEmail1">Password</label>
                  <input type="password" name='password' class="form-control">
                </div>                

                <div class="form-group">
                  <label for="exampleInputEmail1">Confirm Password</label>
                  <input type="password" name='cpassword' class="form-control">
                </div>
                <input type="submit" name="new-password" class="btn btn-primary">
              </form>
            <?php } } else{
                <p>This forget password link has been expired</p>
              }
            }
            ?>
            </div>
          </div>
      </div>

   </body>
</html>

Step 6 – Update New Password into MySQL DB

In step 6, create one php file, which name update-forget-password.php . And add the following code into it:

<?php
if(isset($_POST['password']) && $_POST['reset_link_token'] && $_POST['email'])
{
  include "mydbCon.php";
  
  $emailId = $_POST['email'];

  $token = $_POST['reset_link_token'];
  
  $password = md5($_POST['password']);

  $query = mysqli_query($conn,"SELECT * FROM `users` WHERE `reset_link_token`='".$token."' and `email`='".$emailId."'");

   $row = mysqli_num_rows($query);

   if($row){

       mysqli_query($conn,"UPDATE users set  password='" . $password . "', reset_link_token='" . NULL . "' ,exp_date='" . NULL . "' WHERE email='" . $emailId . "'");

       echo '<p>Congratulations! Your password has been updated successfully.</p>';
   }else{
      echo "<p>Something goes wrong. Please try again</p>";
   }
}
?>

The update-forget-password.php code will store update password into mysql database table. user into database table.

Conclusion

To send forgot password link on email for reset password in PHP; In this tutorial, You have learned how to send reset password link on email in PHP + MySQL with link expiry time. and how to send email using gmail smtp server in PHP.

Recommended PHP Tutorials

Leave a Comment