Skip to content

How to Generate One-Time Password in PHP

In the modern world, almost every service requires a one-time password (OTP).

Generating an OTP is straightforward, but the main challenge is ensuring it is cryptographically unpredictable to prevent service exploitation.

Here, we will show you how to generate a proper OTP.

Generating N-digit Numeric OTP

One of the most commonly used ways of generating an OTP is using the rand() function.

However, rand() is not cryptographically secure and should not be used for authentication.

That’s why, we will demonstrate another method that uses the random function along with an algorithm for creating n-digit numeric OTP.

Let’s check it out:

php generate n-digit OTP

php
<?php

// Function to generate OTP
function generateNumericOTP($n)
{
  // Taking a generator string that consists of
  // all the numeric digits
  $generator = "1357902468";

  // Iterating for n-times and pick a single character
  // from generator and append it to $result

  // Logic for generating a random character from generator
  //     ---generate a random number
  //     ---take modulus of same with length of generator (say i)
  //     ---append the character at place (i) from generator to result

  $result = "";

  for ($i = 1; $i <= $n; $i++) {
    $result .= substr($generator, rand() % strlen($generator), 1);
  }

  // Returning the result
  return $result;
}

// Main program
$n = 6;
print_r(generateNumericOTP($n));

?>

php generate n-digit OTP output

console
561862

Secure N-digit Numeric OTP with random_int()

For production environments, random_int() is recommended as it provides cryptographically secure pseudo-random numbers.

Example of using random_int() for numeric OTP

php
<?php
function generateSecureNumericOTP($n) {
    $otp = '';
    for ($i = 0; $i < $n; $i++) {
        $otp .= random_int(0, 9);
    }
    return $otp;
}

echo generateSecureNumericOTP(6);
?>

Using random_bytes()

PHP 7 provides a new function random_bytes() which is a more secure way of password generation.

Example of using random_bytes() function in PHP

php
<?php 

$bytes = random_bytes(5);
var_dump(bin2hex($bytes));

console
string(10) "05fad18f2f"

What is OTP

A one-time password (OTP) is a password which can be valid for only one login session or transaction, on any digital device.

OTPs help to avoid shortcomings that are associated with static password-based authentication.

One of the most crucial benefits of such passwords is that on the contrary to static passwords, they are safe from replay attacks.

The downside of OTPs is that they are hard for humans to memorize.

Dual-run preview — compare with live Symfony routes.