Send Reset Password Link Email PHP Example


Today in this tutorial, Reset password in core PHP MySQL tutorial. Here, we will learn how to send a reset password link in an email with expire time PHP MySQL.

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

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

[Reset Password Link Send] Email Using PHP - Step By Step

Send Reset Password Link with Expiry time in PHP MySQL

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:

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

<?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());
        }
?>
Step 2: Create Reset Password Form To Send Link In Email

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

This HTML code shows the reset password form.

Now, update the following HTML form 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>Send Reset Password Link with Expiry Time in PHP MySQL - phpcodingstuff.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 - phpcodingstuff.com
            </div>
            <div class="card-body">
              <form action="password-reset.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" 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 a new PHP file named password-reset.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.php file:

<?php
if(isset($_POST['password-reset']) &amp;&amp; $_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.phpcodingstuff.com/reset-password.php?key=".$email."&amp;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 a new password from the user. To create a reset-password.php file.

And update the following PHP and HTML code into the 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'] &amp;&amp; $_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 an update-forget-password.php file to update the new password into the database table.

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

So open the 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>";
    }
}
?>

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


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close