Making otp expire after certain minutes is very important from security of point of view. In order to generate random otp we we use php rand() function. Though, this function generates random number but it is not secured. The otp can be manipulated or guessed by the craker given a considearble amount of time. So, we need to set a time limit on the otp generated and beyond this time the otp will expire and user need to regenerate the otp. So, a secured web application in php needs otp automatically expires after ceratin minutes so that user regenarte otp. This is very important in making security web application
Here, I will talk about to make otp expire after certain minutes say 5 minutes. To achieve this we will ask server time and save the value in a variable $timestamp. To pass this value across session we need to save this value in a php session variable $_SESSION['time'] = $timestamp.
$email = $_POST['email']; // receive the email from front end
$otp = rand(100000, 999999); //generates random otp
$_SESSION['session_otp'] = $otp; // stores the otp into a session variable
$message = "Your one time email verification code is" . $otp; //embed the otp into message.
$sub = "Email verification from Dj Techblog";
$headers = "From : " . "dj@djtechblog.com";
try{
$retval = mail($email,$sub,$message);
$timestamp = $_SERVER["REQUEST_TIME"]; // generate the timestamp when otp is forwarded to user email/mobile.
$_SESSION['time'] = $timestamp; // save the timestamp in session varibale for further use.
if($retval)
{
require_once('verification-form.php'); // send the otp verification page to user
}
}
catch(Exception $e)
{
die('Error: '.$e->getMessage());
}
After user receives the otp via email or sms, he enters the otp in the the verification page sent to him. The entered otp will be sent again to server. We will again record the server time and comapre the current timestamp with the saved timestamp in $_SESSION['time']. If compared value exceeds 300 seconds that is 5 minutes, we declare the OTP as expired.
$otp = $_POST['otp']; //receives the otp entered by the user
$timestamp = $_SERVER["REQUEST_TIME"]; // record the current time stamp
if(($timestamp - $_SESSION['time']) > 300) // 300 refers to 300 seconds
{
echo json_encode(array("type"=>"error", "message"=>"OTP expired. Pls. try again."));
}
else{
if ($otp == $_SESSION['session_otp'])
{
unset($_SESSION['session_otp']);
echo json_encode(array("type"=>"success", "message"=>"Your Email is verified!"));
}
else {
echo json_encode(array("type"=>"error", "message"=>"Email verification failed"));
}
}
In my other articles I have written about how to create otp and send to mobile number using sms.
Recommended read,
Email verification in php using otp
Mobile number verification in php using sms otp
If you like this article, share with your friends. It will inspire me to write more.
Published on Feb 16, 2021