Simple FreeOTP access for PHP

Last Updated or created 2024-05-26

I’ve played with FreeOTP for my own websites in the past, but here is a cleaned up version.

apt-get install qrencode oathtool

Using a webserver with php you can use below simple sniplet to restrict access.

<?PHP
$output = shell_exec('oathtool --totp=sha256 --base32 ################PLACE-SECRET-OUTPUT-HERE-############');
$otp=$_POST["otp"];
$stripped = preg_replace('/\D/', '', $output);
$strippedotp = preg_replace('/\D/', '', $otp);
?>
<form action="" method="post">
OTP: <input type="text" name="otp"><br>
<input type="submit">
</form>
<?PHP
if(strcmp("$strippedotp", "$stripped") == 0)
{ echo "Access"; }
else
{ echo "No Access"; }
?>

bash script to generate secret and qrcode

#!/bin/bash
secret=$(echo 1234567812345678 | base32)
echo "Secret : (place in PHP file)"
echo $secret
qrencode -t ANSI256 -o - $(echo otpauth://totp/Mine:myname?secret=${secret}\&issuer=Mine\&algorithm=SHA256\&digits=6\&period=30) -o qrcode.png -t png -s 5

Above generates a QRcode you can import in FreeOTP

Spread the love

3 thoughts on “Simple FreeOTP access for PHP”

  1. Thanks for the nice sample
    Unfortunately there is a BUG in your bash-script:
    qrencode drops informations after & (ampersand)

  2. === email pastes ======
    > May I bother you with a Question?
    > I experience, that it works when using FreeOTP
    > Using Microsoft Authenticator fails, generates OTPs > different from FreeOTP.
    > Have you experienced similar?
    === email pastes ======
    > OTP-Tools – MSAuthenticator Issue
    > Thanks for your Tools
    > They have helped us to solve the MS Problem:
    > We have found, that the actual Microsoft
    > Authenticator (Android) ignores
    > algorithm=SHA256 and uses SHA1 instead,
    > without creating an error Message.

Leave a Reply

Your email address will not be published. Required fields are marked *