Mobile Number Verification via OTP SMS using PHP

Mobile Number Verification via OTP SMS using PHP

Mobile Number Verification via OTP SMS using PHP

This tutorial will help you:

  • Generate an OTP

  • Send it to a mobile number via SMS

  • Verify the entered OTP on your website

Requirements

  • PHP server (XAMPP/LAMP/WAMP or Live Server)

  • A SMS Gateway API

  • MySQL (for storing OTPs, optional)

Choose an SMS Gateway API

You can use any SMS service provider. Popular options:

In this example, we'll use Fast2SMS (free tier in India)
You’ll need to:

  1. Create an account

  2. Get the API key from your dashboard

Step-by-Step Implementation

1. HTML Form to Enter Mobile Number

<form method="POST" action="send_otp.php"> <input type="text" name="mobile" placeholder="Enter Mobile Number" required> <button type="submit">Send OTP</button> </form>

2. PHP Script to Send OTP (send_otp.php)

<?php session_start(); $mobile = $_POST['mobile']; $otp = rand(100000, 999999); // generate 6-digit OTP $_SESSION['otp'] = $otp; $_SESSION['mobile'] = $mobile; // Replace with your Fast2SMS API key $apiKey = "YOUR_FAST2SMS_API_KEY"; $msg = urlencode("Your OTP is $otp"); $url = "https://www.fast2sms.com/dev/bulkV2?authorization=$apiKey&route=v3&sender_id=TXTIND&message=$msg&language=english&flash=0&numbers=$mobile"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array("cache-control: no-cache") )); $response = curl_exec($curl); curl_close($curl); echo "OTP sent to $mobile"; header("Location: verify_otp.php"); exit(); ?>

3. OTP Verification Form (verify_otp.php)

<form method="POST" action="check_otp.php"> <input type="text" name="otp" placeholder="Enter OTP" required> <button type="submit">Verify</button> </form>

4. Check OTthe P (check_otp.php)

<?php session_start(); $userOtp = $_POST['otp']; if ($_SESSION['otp'] == $userOtp) { echo "✅ OTP Verified Successfully!"; // You can mark the user as verified in DB } else { echo "❌ Invalid OTP. Please try again."; } ?>

Optional: Store OTP in Database (More secure)

Instead of using $_SESSION, You can store:

  • mobile

  • otp

  • timestamp

Then, verify within a time limit (e.g., 5 minutes).

Security Tips

  • Expire OTPs after 5-10 minutes.

  • Rate limit OTP requests per number/IP.

  • Never expose your API key in frontend code.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close