How To Set The Expiry Period For A Reset Password Link.

Listen Audio
0:00 / 0:00
How to set the expiry period for a reset password link. image

You may be wondering how to implement or set a password link expiry time after requesting a reset password. So we can implement using PHP and Backend MySql. We will divide the content in to three sections.

1, create an input text box a user entered their email

<form class="login-form"  id="vform" action="" method="post">
            Please Enter Your email address
		    You will receive an email with instructions on how to reset your password.
			<input type="email" name="email" id="enter_email" onkeyup="update_button()" onblur ="validate_email();"  placeholder="Enter Email" pattern="[A-Za-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" />
		<button type="submit" name="reset-password" id="buttonb" disabled>Submit</button>
	</form>

the output will be as below

                              

include this PHP link at the top of your HTML home page.

A JavaScript function that will enable and disable the submit button based on the input value.

function update_button() {
   var email_value = document.getElementById("enter_email").value;  
	 if(email_value.length<10) { 
            document.getElementById('buttonb').disabled = true; 
        }
        else { 
            document.getElementById('buttonb').disabled = false;
            document.getElementById('buttonb').style.background = "#EDBD11";
            document.getElementById('buttonb').style.color = "black";
            document.getElementById('buttonb').style.cursor = "pointer";
            document.getElementById("buttonb").onmouseover = function() 
           {
           this.style.backgroundColor = "green";
           this.style.color="white";
           this.style.borderRadius="25px";
           this.style.border="none";
           this.style.textTransform = "uppercase";
           }
           document.getElementById("buttonb").onmouseout = function() 
           {
           this.style.backgroundColor = "#EDBD11";
           this.style.color = "black";
           this.style.borderRadius="5px";
           this.style.textTransform = "lowercase";
           }
        }
    }

then implement a PHP code to send a password expiry time to the email (app_logic.php file)

$error = [];
$user_id = "";
$username = "";
global $conn;
if (isset($_POST['reset-password'])) {
  $email = mysqli_real_escape_string($conn, $_POST['email']);
  // ensure that the user exists on our system
  $query = "SELECT email, firstname, lastname FROM users WHERE email='$email'";
  $resultset = mysqli_query($conn, $query);
  $usernames = mysqli_fetch_assoc($resultset);
  if(empty($usernames)){
	  array_push($error, "");
  }
  else{
  $firstname= $usernames['firstname'];
  $lastname= $usernames['lastname'];
  }
  if (empty($email)) {
    array_push($error, "Your email is required");
  }
  else if(mysqli_num_rows($resultset) <= 0) {
    array_push($error, "Sorry, no user exists on our system with email ID
".$email.""); } // generate a unique random token of length 50 $token = bin2hex(random_bytes(50)); $cenvertedTime =date('Y-m-d', strtotime(' + 1 days')); if (count($error) == 0) { //delete old token when new token requested $sql1 = "DELETE FROM password_reset WHERE email='$email'"; $resultdelete = mysqli_query($conn, $sql1); // store token in the password-reset database table against the user's email $sql = "INSERT INTO password_reset(email, token, link_expired) VALUES ('$email', '$token', '$cenvertedTime')"; $results = mysqli_query($conn, $sql); if($results){ $inserted_id = mysqli_insert_id($conn); $user_check = "SELECT link_expired FROM password_reset WHERE id='$inserted_id' LIMIT 1"; $result = mysqli_query($conn, $user_check); $date = mysqli_fetch_assoc($result); $created_at = $date['link_expired']; $created_at = date("F j, Y ", strtotime($created_at)); // Send email to user with the token in a link they can click on $auto = date(Y); $to = $email; $sent_date = date("F j, Y "); $subject = "Password Reset Request for account on G3TECHDESIGN.COM"; $msg = " <bod> <html> Dear ".$firstname." ".$lastname." We have sent you this email because recently you requested to rest your account password. If you did not requested this change, please contact account administrator at info@g3techdesign.com to protect your privacy. If you do so, clik the button below to reset your account password. Create New Password If the link is not working properly you may copy the following url to your favorite browser. Here is a link https://www.g3techdesign.com/password-recovery/new_pass.php?token=" . $token ."

This link will be expire on ". $created_at .". Regards, This email was sent to: ". $to ." on ". $sent_date ." Copyright © ". $auto ." All Rights Reserved. <<body> <html> "; $msg = wordwrap($msg,70,"\r\n"); // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= 'From: Do-Not-Reply noreply@g3techdesign.com'. "\r\n"; mail($to, $subject, $msg, $headers); header('location: ' . BASE_URL . 'pending.php?email=' . $email); } else { array_push($error, "Something want wrong"); // redirect to public area header('location: '. BASE_URL . 'password-recovery/enter_email.php'); exit(0); } } }

finally when the user click on the link forward to page that the user creat a new  password. it check if the link is expired or not.

if (isset($_POST['new_password'])) {
  $key_id = mysqli_real_escape_string($conn, $_POST['key_value_id']);
  $new_pass = mysqli_real_escape_string($conn, $_POST['new_pass']);
  $new_pass_c = mysqli_real_escape_string($conn, $_POST['new_pass_c']);
// Grab to token that came from the email link
  $token = $_GET['token'];
  if (empty($new_pass) || empty($new_pass_c)) array_push($error, "Password is required
");
  if ($new_pass !== $new_pass_c) array_push($error, "Password do not match");
  if (count($error) == 0) {
   $new_pass = md5($new_pass);
    // select email address of user from the password_reset table 
    $sql = "SELECT email, link_expired FROM password_reset WHERE token= '$key_id'  LIMIT 1";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
      $row = mysqli_fetch_assoc($result);
      $email = $row['email'];
      $link_expired = $row['link_expired'];
      $currentDateTime = date('Y-m-d H:i:s');
      if($currentDateTime < $link_expired){
	  //collect user information based on email account
      $sql_result = "SELECT firstname,  lastname FROM users WHERE email= '$email'  LIMIT 1";
      $result_info = mysqli_query($conn, $sql_result);
      $results = mysqli_fetch_assoc($result_info);
      $fname = $results['firstname'];
      $lname = $results['lastname'];
      $sqlupdate = "UPDATE users SET password='$new_pass' WHERE email ='$email' LIMIT 1";
      $results = mysqli_query($conn, $sqlupdate);
      $to = $email;
      $auto = date(Y);
      $sent_date = date("F j, Y ");
      $subject='Password Succesfuly Updated';
      $message="
            
              
            
	Dear ".$fname." ".$lname."
	This notice confirms that your account password was successfully changed
        Regards, 
        This email was sent to: ". $to ." on ". $sent_date ."                    
		 Copyright © ". $auto ." All Rights Reserved.    
	    
         
		  ";
	    $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= 'From: Do-Not-Reply noreply@g3techdesign.com'. "\r\n";
        
      mail($to, $subject, $message, $headers);
      $_SESSION['message'] = " Your Password was successfully reseted. Try to login with your new password.";
      header('location: ' . BASE_URL . 'login.php');
      exit(0);
      }else{
		$_SESSION['messages'] = " The link we have sent you was expired. Try to request a new link to reset your password.";
		 header('location: ' . BASE_URL . 'password-recovery/new_pass.php');
      exit(0);
      }
      }else{
	$_SESSION['messages'] = " This Account is invalid or reset password link invalid.";
        header('location: ' . BASE_URL . 'password-recovery/new_pass.php');
      exit(0);
     }
  }
}

 



Leave a non public comment how to improve it.



Characters Remaining

We are sorry for your bad experience. Leave a non public comment how to improve it.



Characters Remaining

Related Posts (11)

How to create a custom archive page template on your website layout image
Test the video layout design(Upload and Store video to MySQL Database with PHP) image
Getting User Device Location and Updating Database image
Send A verification email when a new user registered  image
How to Send Verification link when a new user register image
How to limit the number of login attempts  image
How to limit the number of login attempt using PHP part 2(PHP functionality) image
Download file using PHP image
Inactive user enforce to login (SESSION expired) or Limmit the resource image
How to count page viewers based on the IP Address of the device image
Pagination in PHP image

Share this on

Search


Archives

No archives data found yet in 2016.

Find Us on Facebook

Subscribe for new updates



Back to Top