OTP Verification in PHP
In this lesson: Generate, store, expire and verify OTP in PHP with sessions or MySQL — secure flow with resend limit.
What is OTP verification
OTP (One-Time Password) verification confirms a user really controls an email or phone. You generate a short random code, send it to them, and ask them to type it back. If it matches (and has not expired), they are verified. It is a common extra security step for signup, login and payments.
Generate an OTP
<?php
$otp = random_int(100000, 999999); // secure 6-digit code
echo $otp; // e.g. 483920
?>
Use random_int (not rand) for a secure, hard-to-guess code. A 6-digit range gives 900,000 possibilities.
Store it with an expiry
<?php
session_start();
$_SESSION["otp"] = $otp;
$_SESSION["otp_expiry"] = time() + 300; // valid 5 minutes
?>
Store the OTP and an expiry time in the session (server-side). Never put it in a hidden field or cookie, where the user could read or change it.
Send the OTP
Deliver the code by email or SMS. For email, use PHPMailer over SMTP:
<?php
// send by email (simplified)
$subject = "Your OTP";
$body = "Your code is: $otp (valid 5 minutes)";
// $mail->send(); with PHPMailer, or an SMS gateway API
?>
The user receives the code and enters it on the next screen. PHP already has the correct value stored for comparison.
Verify what the user enters
<?php
session_start();
$entered = $_POST["otp"] ?? "";
if (time() > ($_SESSION["otp_expiry"] ?? 0)) {
echo "OTP expired";
} elseif ($entered == ($_SESSION["otp"] ?? null)) {
echo "Verified successfully";
unset($_SESSION["otp"]); // one-time use
} else {
echo "Wrong OTP";
}
?>
First check expiry, then compare the entered code to the stored one. On success, remove the OTP from the session so it cannot be reused — that is the "one-time" part.
Common mistakes
- Using
rand(). Userandom_intfor a secure, unpredictable code. - Storing the OTP client-side. Keep it in the session/database, never in a cookie or hidden field.
- No expiry. Always set and check an expiry time.
- Not clearing after use. Remove the OTP once verified so it is truly one-time.
Summary
- OTP verification confirms a user controls an email or phone.
- Generate securely with
random_int. - Store the OTP and an expiry server-side (session or database).
- Send by email or SMS, then compare the entered code.
- Check expiry and clear the OTP after a successful match.
Next, deliver it via email in PHP, or protect the flow with sessions.
Frequently Asked Questions
What is an OTP?
How do I generate an OTP in PHP?
random_int(100000, 999999) for a 6-digit code. Avoid rand() for anything security-related, since it is more predictable.