PHP program to generate a numeric one-time password

To generate a numeric one-time password in PHP, you can use the rand() function to randomly select digits from a string of numbers. This method ensures each digit is chosen randomly for better security ?

Example

<?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;
echo "The one time password generated is: ";
echo generate_otp($num);
?>

Output

The one time password generated is: 52471609

How It Works

The generate_otp() function takes the desired length as a parameter. It defines a string containing digits 0-9 in a shuffled order. The function then iterates through the specified length, randomly selecting one digit at a time using rand() and substr(). Each selected digit is concatenated to build the final OTP string.

Alternative Method Using mt_rand()

For better randomness, you can use mt_rand() instead of rand() ?

<?php
function generate_secure_otp($length)
{
    $otp = "";
    for ($i = 0; $i < $length; $i++) {
        $otp .= mt_rand(0, 9);
    }
    return $otp;
}

$length = 6;
echo "Secure OTP: " . generate_secure_otp($length);
?>

Output

Secure OTP: 384729

Conclusion

Both methods effectively generate numeric OTPs in PHP. The mt_rand() approach provides better randomness and is recommended for security-sensitive applications where unpredictability is crucial.

Updated on: 2026-03-15T09:04:13+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements