OTP (One Time Password) functionality in PHP with an expiration time
To implement OTP (One Time Password) functionality in PHP with an expiration time, you can use the $_SESSION variable to store the OTP and its creation time. Here's an example of how to generate an OTP with an expiration time:
// Function to generate a random OTP function generateOTP($length = 6) { $characters = '0123456789'; $otp = ''; $max = strlen($characters) - 1; for ($i = 0; $i < $length; $i++) { $otp .= $characters[mt_rand(0, $max)]; } return $otp; } // Function to check if the OTP is still valid function isOTPValid($otp, $createdTime, $expirationTime) { // Compare the provided OTP with the stored OTP if ($otp === $_SESSION['otp'] && time() <= $createdTime + $expirationTime) { return true; } else { return false; } } // Example usage session_start(); $expirationTime = 300; // Expiration time in seconds (5 minutes) $otp = generateOTP(); $_SESSION['otp'] = $otp; $_SESSION['otp_created_time'] = time(); echo "Your OTP: " . $otp; // Example OTP verification $enteredOTP = '123456'; // Replace with the value entered by the user if (isOTPValid($enteredOTP, $_SESSION['otp_created_time'], $expirationTime)) { echo "OTP is valid."; } else { echo "OTP is invalid or has expired."; }
In this example, the generateOTP function generates a 6-digit random OTP. The isOTPValid function checks whether the provided OTP matches the stored OTP and whether the expiration time has passed.
Adjust the expirationTime variable as needed, and make sure to handle the expiration logic according to your application's requirements.
Komentar
Posting Komentar