A very easy PHP function to create One-Time Password (OTP)

Max Wang
1 min readJun 12, 2023

--

There are many open-source libraries in PHP for generating One-Time Password (OTP), but they are all quite complex. If your application scenario is simple, this simple function may meet your needs.

The function is:

<?php

/**
* @param string $sercet_key A string of the secret key.
* @param int $time_step Time to use for the OTP code, defaults to 60 seconds.
* @param int $length Length of the OTP code, defaults to 6.
* @return string
*/
function generateOTP(string $sercet_key, int $time_step = 60, int $length = 6): string
{
$counter = floor(time() / $time_step);
$data = pack("NN", 0, $counter);
$hash = hash_hmac('sha1', $data, $sercet_key, true);
$offset = ord(substr($hash, -1)) & 0x0F;
$value = unpack("N", substr($hash, $offset, 4));
$otp = ($value[1] & 0x7FFFFFFF) % pow(10, $length);

return str_pad(strval($otp), $length, '0', STR_PAD_LEFT);
}

echo generateOTP("123");

Note: SHA1 is used in this function to generate hash.

I used this function in my project and it worked very well.

--

--