How to Generate One-Time Password in PHP

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

OTP may be generated easily by a developer. However, there is an essential challenge: not to create a predictive password to avoid the exploitation of the service.

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

Watch a course Learn object oriented PHP

Generating N-digit Numeric OTP

One of the most commonly used ways of generating OTP is using the random function.

Yet, this option can not be trustworthy enough.

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

// 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

  // Login 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));

?>
561862

Using random_bytes()

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

$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
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.