PHP Library for Google Authenticator (Two Factor Authentication 2FA)

Posted on January 12, 2019 at 8:49 pm

Here is a very simple and working PHP library for Google Authenticator:

With that library you can easily integrate two factor (2FA) authentication like this:

require_once 'PHPGangsta/GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
// Save this $secret in a database and load it from the database the next time
// The $secret variable should be unique for each user
$secret = $ga->createSecret();
echo "Secret is: ".$secret."<br /><br />";
// CHange 'Your App Name' with your application name, i.e John App
$qrCodeUrl = $ga->getQRCodeGoogleUrl('Your App Name', $secret);
echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."<br /><br />";
// Show the QR code image to the user so he can scan it with the Google Authenticator app:
echo "<img src='".$qrCodeUrl."' /><br /><br />";
// Here we should get the code sent by the user via a POST field
$oneCode = trim($_POST['code']); //$ga->getCode($secret);
echo "Checking Code '$oneCode' and Secret '$secret':<br /><br />";
$checkResult = $ga->verifyCode($secret, $oneCode, 2);    // 2 = 2*30sec clock tolerance
if ($checkResult) {
    echo '<font color="green">OK</font>';
} else {
    echo '<font color="red">FAILED</font>';

To allow an user to reset the 2FA code, you can generate a “master code” when the user activates the Google Authenticator option, then show it to the user one time and/or send it to the user via email, and then save it in the database (not in plain text but hashed, i.e using sha512 hash). Then if the user loses the mobile device, he can enter that specific “master code” to bypass the Google Authenticator code and be able to still login in his account. For better security, you should also allow the user to change his $secret code used for Google Authenticator.

Receive updates via email

Other Posts

Updated Posts