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

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 experiance. Leave a non public comment how to improve it.



Characters Remaining

Related Posts (12)

Getting User Device Location and Updating Database image

Getting User Device Location and Updating Database

Author image
By JOHN Mon Feb 19, 2024 at 12:31 PM (3 months ago)
Updated On Sat Mar 09, 2024 at 07:59 AM (2 months ago)

Read More »
How to create a custom archive page template on your website layout image

How to create a custom archive page template on your website layout

Author image
By JOHN Thu Nov 17, 2022 at 08:00 AM (2 years ago)
Updated On Thu Jan 05, 2023 at 06:24 PM (one year ago)

Read More »
Test the video layout design(Upload and Store video to MySQL Database with PHP) image

Test the video layout design(Upload and Store video to MySQL Database with PHP)

Author image
By JOHN Sat Nov 05, 2022 at 05:15 PM (2 years ago)
Updated On Wed Nov 09, 2022 at 06:39 PM (2 years ago)

Read More »
Send A verification email when a new user registered  image

Send A verification email when a new user registered

Author image
By JOHN Tue Dec 07, 2021 at 04:53 PM (2 years ago)
Updated On Tue Nov 08, 2022 at 06:58 AM (2 years ago)

DGDFH

Read More »
How to Send Verification link when a new user register image

How to Send Verification link when a new user register

Author image
By JOHN Fri Oct 15, 2021 at 07:49 AM (3 years ago)
Updated On Fri Nov 04, 2022 at 05:00 PM (2 years ago)

This tutorial teaches you to build an email verification script from scratch

Read More »
How to limit the number of login attempts  image

How to limit the number of login attempts

Author image
By JOHN Sat Oct 31, 2020 at 10:19 PM (4 years ago)
Updated On Wed Nov 09, 2022 at 04:38 PM (2 years ago)

It is one of a security mechanism to restrict an authorized user from access the systems and locked the account if it's necessary. In this tutorial we will create a simple login system to demonstrate the implementation using PHP and MySQL. Let's digest it...

Read More »
How to limit the number of login attempt using PHP part 2(PHP functionality) image

How to limit the number of login attempt using PHP part 2(PHP functionality)

Author image
By JOHN Tue Sep 22, 2020 at 06:47 PM (4 years ago)
Updated On Wed Nov 09, 2022 at 05:06 PM (2 years ago)

To protect spam or junk email registration the system have to verify user email by sending a verification link to a  proven email address[] 

Read More »
Download file using PHP image

Download file using PHP

Author image
By MEWDED Wed Sep 02, 2020 at 10:04 AM (4 years ago)
Updated On Sat Nov 12, 2022 at 09:10 AM (2 years ago)

Short explanation 

Read More »
Inactive user enforce to login (SESSION expired) or Limmit the resource image

Inactive user enforce to login (SESSION expired) or Limmit the resource

Author image
By MEWDED Tue Sep 01, 2020 at 04:24 AM (4 years ago)
Updated On Sat Nov 12, 2022 at 09:35 AM (2 years ago)

Quick description

Read More »
How to count page viewers based on the IP Address of the device image

How to count page viewers based on the IP Address of the device

Author image
By MEWDED Thu Aug 27, 2020 at 04:37 PM (4 years ago)
Updated On Sat Nov 12, 2022 at 06:57 PM (2 years ago)

Hi, today we will walk you through how to implement to count the page viewers base on IP address like Youtube or Facebook 

Read More »
Pagination in PHP image

Pagination in PHP

Author image
By MEWDED Fri Aug 14, 2020 at 02:58 PM (4 years ago)
Updated On Fri Nov 04, 2022 at 03:08 PM (2 years ago)

Hi there ????, 

TODAY we are walking ????‍?? together to show you how to implement pagination in PHP

Read More »
Author Title image

Author Title

Author image
By JOHN Mon Jul 13, 2020 at 04:19 AM (4 years ago)
Updated On Fri Nov 04, 2022 at 03:08 PM (2 years ago)

Author description

Read More »

Share this on

Search


Archives

No archives data found yet in 2025.

No archives data found in 2016.

Find Us on Facebook

Subscribe for new updates




Back to Top