Send Reset Password Link Email PHP
Php 22-Sep-2021

Send Reset Password Link Email PHP

Reset password in core PHP MySQL tutorial. Here, we will show you how to send reset password link in email with expire time PHP MySQL.

Sometimes security reasons, you may want to send reset password link with expire time of your website in PHP MySQL.

So, this php generates and sends a password reset link with token tutorial, we will guide step by step on how to generate reset/forget password link with expire time in PHP MySQL and send it to link in email using PHPMailer.

Send Reset Password Link with Expiry time in PHP MySQL

Simple reset forget password with email link in PHP MySQL by using the following steps:

  • Step 1: Create a Database Connection PHP File
  • Step 2: Create Forget Password Form to Send Link In Email
  • Step 3: Send Link in Email and Store Token with Expire time PHP file
  • Step 4: Create a Reset Password Form to Update New Password
  • Step 5: Update Forgot Password PHP File

Step 1: Create a Database Connection PHP File

In this step, create a file name db.php and update the following code into db.php file:

<?php
    $servername='localhost';
    $username='root';
    $password='';
    $dbname = "my_db";
    $conn=mysqli_connect($servername,$username,$password,"$dbname");
      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
        }
?>

Note that, This code is used to create a MySQL database connection in PHP project.

Step 2: Create Forget Password Form to Send Link In Email

In this step, create a forget-password.php file and update the below PHP and HTML code into forget-password.php file.

Note that, This HTML code shows the forget password form.

Now, update the following html form into forget-password.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</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
            </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 3: Send Link in Email and Store Token with Expire time PHP file

In this step, create new PHP file named password-reset-token.php. This file PHP code will generate a reset password link with expire time. And then send this link via email and store it into MySQL DB.

To update the following php code into password-reset-token.php file:

<?php
if(isset($_POST['password-reset-token']) && $_POST['email'])
{
    include "db.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 = "your_email_id@gmail.com";
    // 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='your_gmail_id@gmail.com';
    $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";
  }
}
?>

Step 4: Create a Reset Password Form to Update New Password

In this step, create a new form in php will get new password from user. So create reset-password.php file.

And update the following php and html code into reset-password.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>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 "db.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 5: Update Forgot Password PHP File

Now, create update-forget-password.php file to update the new password into database table.

This PHP file code will store update password into mysql database table. user into database table.

So open update-forget-password.php file and update the following php code into it:

<?php
if(isset($_POST['password']) && $_POST['reset_link_token'] && $_POST['email'])
{
include "db.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>";
}
}
?>

Conclusion

Send reset password link with expiry time in php mysql tutorial, you have learned how to send forget/reset password link in email with expire time in PHP MySQL.