Paramclasses Academy - Blog

Tutorials Details

←
Post 17 of 19
→

What is OTP SMS Integration: How to Send Secure Verification Codes ?

What is OTP SMS Integration: How to Send Secure Verification Codes ?

November 27, 2026

1. Introduction

Modern websites and mobile applications require reliable verification systems to protect user accounts, prevent unauthorized access, and confirm mobile number ownership.

One commonly used verification method is OTP-based authentication. OTP stands for One-Time Password. It is a temporary security code that can be delivered to a user's registered mobile number through SMS.

Businesses use OTP verification during account registration, login, password recovery, payment confirmation, and other security-related activities.

Unlike ordinary SMS notifications, OTP messages require additional security measures, including secure code generation, expiration periods, verification attempt limits, and protection against repeated requests.

In this tutorial, we will learn how OTP verification works and implement a practical SMS-based verification system using PHP and an SMS API.

2. Learning Objectives

After completing this tutorial, you will be able to:

  • Understand OTP-based authentication.

  • Generate secure verification codes using PHP.

  • Send OTP messages through an SMS API.

  • Implement OTP expiration and verification.

  • Limit incorrect verification attempts.

  • Prevent repeated and unauthorized OTP requests.

  • Understand SMS authentication security limitations.

  • Integrate verification into websites and applications.

3. What Is OTP?

OTP stands for One-Time Password.

It is a temporary security code used to verify a user's access to a registered communication channel or authenticate a particular activity.

Unlike permanent passwords, OTP codes are designed for short-term use and should become invalid after successful verification.

A typical SMS verification code contains six numerical digits.

Example:

Your ABC App verification code is 482619. Valid for 5 minutes. Do not share this code with anyone.

OTP codes should be generated using a cryptographically secure random number generator rather than predictable sequences.

4. Common Applications of OTP SMS

4.1 User Registration

Websites can verify whether new users have access to their submitted mobile numbers.

4.2 Login Verification

Applications can request an additional verification code during account login.

4.3 Password Recovery

An OTP can form part of an account recovery process after appropriate security checks.

4.4 Payment Authentication

Financial applications can use verification codes to confirm qualifying transactions.

4.5 Mobile Number Verification

Businesses can verify access to a submitted mobile number before activating an account or service.

5. How Does OTP Verification Work?

The simplified verification workflow is:

User Request → Backend Server → Secure OTP Generation → SMS API → Mobile Phone → OTP Submission → Server Verification.

First, the application receives a verification request. The backend generates a random code and records its expiration time.

The server submits the code through an SMS provider. After receiving the message, the user enters the code into the application.

The backend checks whether the submitted code is correct, unexpired, unused, and within the permitted verification attempt limit.

Successful verification allows the associated registration or authentication process to continue.

6. Requirements for OTP Integration

Prepare the following before implementing the practical example:

  • PHP 8 or later.

  • XAMPP or another PHP development environment.

  • Enabled PHP cURL extension.

  • MSG91 messaging account.

  • Valid API authentication key.

  • Configured OTP content template.

  • Applicable DLT registration and sender configuration.

  • Sufficient messaging credits.

  • An authorized test mobile number.

Businesses sending OTP messages in India must satisfy applicable telecom registration and template requirements.

Official TRAI sender guidance:

https://www.trai.gov.in/advice-to-senders

7. Generating a Secure OTP in PHP

PHP provides the random_int() function for generating cryptographically secure random integers.

Example:

<?php

$otp = sprintf(
    '%06d',
    random_int(0, 999999)
);

The random_int() function generates an unpredictable integer, while sprintf() ensures that the output contains exactly six digits, including leading zeros when necessary.

Never display generated OTP codes in a public API response or store them in application logs.

Official PHP documentation:

https://www.php.net/manual/en/function.random-int.php

8. Configuring the OTP SMS Template

Create an applicable DLT-approved message template and configure it within your messaging provider's dashboard.

Illustrative template:

Your ABC App verification code is {VAR1}. Valid for 5 minutes. Do not share this code with anyone.

Here, VAR1 represents the dynamically generated verification code.

Copy the configured MSG91 Template ID and verify that its variable name matches the API request.

This example uses the standard template-based SMS API, with OTP generation and verification handled by PHP. Providers also offer dedicated managed OTP services.

Official MSG91 SMS API documentation:

https://docs.msg91.com/sms/send-sms

9. Practical OTP SMS Integration Using PHP

This exercise demonstrates one complete OTP verification challenge through the terminal. It is designed for learning before implementing a public website endpoint.

Step 1: Create a Project Folder

Create the following folder inside XAMPP:

C:\xampp\htdocs\otp-verification

Create a file named otp.php.

Step 2: Configure API Credentials

Open PowerShell inside the project folder and configure the following environment variables:

$env:MSG91_AUTHKEY="YOUR_AUTH_KEY"
$env:MSG91_TEMPLATE_ID="YOUR_TEMPLATE_ID"
$env:SMS_TEST_MOBILE="YOUR_AUTHORIZED_NUMBER"

Replace the placeholders with valid configuration values. Use the Indian country code 91 without the plus sign.

Step 3: Write the PHP Code

<?php

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit('CLI access only.');
}

$key = getenv('MSG91_AUTHKEY');
$template = getenv('MSG91_TEMPLATE_ID');
$mobile = getenv('SMS_TEST_MOBILE');

if (!$key || !$template || !$mobile) {
    exit("Missing configuration.\n");
}

if (!preg_match('/^91[6-9][0-9]{9}$/', $mobile)) {
    exit("Invalid mobile number.\n");
}

if (!function_exists('curl_init')) {
    exit("Enable PHP cURL.\n");
}

// Generate a secure six-digit OTP
$otp = sprintf('%06d', random_int(0, 999999));

$otpHash = password_hash($otp, PASSWORD_DEFAULT);
$expiresAt = time() + 300;

// Prepare the SMS request
$payload = [
    'template_id' => $template,
    'recipients' => [
        [
            'mobiles' => $mobile,
            'VAR1' => $otp
        ]
    ]
];

$ch = curl_init(
    'https://control.msg91.com/api/v5/flow'
);

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'authkey: ' . $key,
        'Content-Type: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode(
        $payload,
        JSON_THROW_ON_ERROR
    ),
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_SSL_VERIFYHOST => 2
]);

$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

unset($otp, $payload);

$result = is_string($response)
    ? json_decode($response, true)
    : null;

if (
    $status < 200 ||
    $status >= 300 ||
    !is_array($result) ||
    ($result['type'] ?? '') !== 'success'
) {
    exit("SMS submission failed or uncertain.\n");
}

echo "OTP request accepted.\n";

// Allow a maximum of five attempts
for ($attempt = 1; $attempt <= 5; $attempt++) {

    if (time() >= $expiresAt) {
        exit("OTP expired.\n");
    }

    echo "Enter OTP: ";
    $input = fgets(STDIN);

    if ($input === false) {
        exit("Verification cancelled.\n");
    }

    $enteredOtp = trim($input);

    if (time() >= $expiresAt) {
        exit("OTP expired.\n");
    }

    if (
        preg_match('/^[0-9]{6}$/', $enteredOtp) &&
        password_verify($enteredOtp, $otpHash)
    ) {
        unset($otpHash);
        exit("Mobile verification successful.\n");
    }

    echo "Incorrect OTP. Remaining attempts: "
        . (5 - $attempt) . "\n";
}

unset($otpHash);

echo "Verification attempt limit reached.\n";

Step 4: Execute the Program

Run the following command:

C:\xampp\php\php.exe otp.php

When the SMS request is accepted, enter the received verification code in the terminal.

Expected successful output:

OTP request accepted.
Enter OTP: ******
Mobile verification successful.

Valid credentials and an approved template are required. Executing this example submits a real SMS request, and messaging charges may apply.

10. Understanding the PHP Code

The random_int() function generates a secure verification code.

The password_hash() function creates a hash for local verification rather than retaining the original OTP in the verification state.

The expiration time is calculated by adding 300 seconds to the current server time.

The cURL functions submit an authenticated JSON request to the SMS provider.

The password_verify() function checks the entered code against the stored hash.

The verification loop permits a maximum of five attempts for the current challenge.

Successful verification terminates the process, preventing reuse within that challenge.

11. Integrating OTP Verification Into a Website

For a production website, separate OTP submission and verification into protected backend operations.

A typical implementation includes:

  • A mobile number submission form.

  • A Send OTP backend endpoint.

  • A verification code input form.

  • A Verify OTP backend endpoint.

  • A persistent database or Redis store.

  • A secure session linked to the verification challenge.

Store the challenge identifier, intended mobile number, verification purpose, expiration time, attempt count, and verification status.

Use a server-protected keyed hash or managed OTP service for persistent verification records.

Verification must be performed atomically to prevent concurrent requests from using the same code multiple times.

12. OTP Expiration, Resend and Rate Limiting

A verification code should remain valid only for a short period.

For example, an application may use a five-minute expiration period, five verification attempts, and a 60-second resend cooldown.

These values are illustrative security settings.

Production systems must enforce persistent limits across sessions, accounts, mobile numbers, and relevant IP addresses.

Generating a new code should invalidate the previous challenge without resetting the overall failed-attempt counter.

Rate limiting also protects businesses against excessive SMS charges and automated OTP abuse.

13. OTP Security Best Practices

  • Generate codes using cryptographically secure randomness.

  • Never expose OTP codes in public responses or logs.

  • Keep SMS API credentials on the backend.

  • Use HTTPS for communication.

  • Enforce expiration and one-time usage.

  • Restrict verification and resend attempts.

  • Bind each code to its intended user and purpose.

  • Monitor suspicious authentication activity.

SMS verification is vulnerable to phishing, SIM swapping, and mobile number reassignment. It should not be treated as proof of a person's legal identity.

For sensitive applications, consider stronger authentication methods such as passkeys.

Official NIST authentication security guidance:

https://pages.nist.gov/800-63-4/sp800-63b.html

14. Common OTP Integration Problems

OTP Not Received: Review the delivery report, mobile number, sender configuration, and template approval.

Invalid API Key: Verify the server-side authentication configuration.

Incorrect OTP: Check the challenge association and submitted code format.

Expired OTP: Request a new code after the applicable cooldown.

Repeated OTP Requests: Implement persistent rate limits and abuse prevention.

15. Frequently Asked Questions

Q1. Is a six-digit OTP secure?

It can support verification when combined with secure generation, expiration, attempt limits, and other security controls.

Q2. Can OTP integration be implemented in CodeIgniter?

Yes. OTP generation, SMS submission, and verification can be organized into CodeIgniter services, controllers, and persistent storage.

Q3. Does SMS API success confirm verification?

No. The user must successfully complete the verification challenge.

Q4. Can an OTP be reused?

No. A successfully verified code should become invalid.

16. Conclusion

OTP SMS integration provides a practical method of verifying mobile number access and supporting application authentication.

By combining secure OTP generation, SMS API integration, expiration management, verification attempt limits, and protected backend processing, developers can implement reliable verification workflows.

Production systems should also enforce persistent abuse prevention controls and use stronger authentication methods when required by the application's security needs.

←
Post 17 of 19
→