PHP program to generate a numeric one-time password


To generate a numeric one-time password in PHP, the code is as follows −

Example

 Live Demo

<?php
function generate_otp($n)
{
   $gen = "1357902468";
   $res = "";
   for ($i = 1; $i <= $n; $i++)
{
   $res .= substr($gen, (rand()%(strlen($gen))), 1);
}
   return $res;
}
$num = 8;
print_r("The one time password generated is :");
print_r(generate_otp($num));
?>

Output

The one time password generated is :52471609

A function named ‘generate_otp’ is defined that takes the length as a parameter. This is the length of the password that needs to be generated. A number that contains 0 to 9 numbers is defined and the length is iterated over and a random number that contains these 0 to 9 numbers randomly is generated. The length is defined and the function is called on this length. This generates a numeric password and displays it on the console.

Updated on: 02-Jul-2020

671 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements