Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 46

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.

💡 The rule: generate securely, store server-side with an expiry, and compare the entered code to the stored one.

Generate an OTP

<?php
  $otp = random_int(100000, 999999);  // secure 6-digit code
  echo $otp;   // e.g. 483920
?>
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";
  }
?>
Verified successfully

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(). Use random_int for 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?
An OTP (One-Time Password) is a short code, usually 4-6 digits, sent to a user to confirm their identity — for example during signup or login. It is valid only once and for a short time, which makes it a strong extra check.
How do I generate an OTP in PHP?
Use a secure random function like random_int(100000, 999999) for a 6-digit code. Avoid rand() for anything security-related, since it is more predictable.
Where should I store the OTP?
Store it server-side — in the session or database — along with an expiry time, never in a hidden form field or cookie where a user could read or change it. Compare the entered code against the stored one.
Why does an OTP need an expiry?
An OTP should work only for a few minutes. Storing an expiry time and rejecting old codes limits the window an attacker has and prevents reusing a leaked code later.
How do I actually send the OTP to the user?
By email (using PHPMailer/SMTP) or by SMS through an SMS gateway API. The PHP generates and stores the OTP, then calls the email or SMS service to deliver it to the user.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicForgot Password Reset Your progress: 46 / 50 (92%) · Lesson 47 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free