How to setup Google two factor authentication on your website

Setting up Google's two factor authentication is fairly simple. Thanks to Henrik Schack for writing the WordPress Google Authenticator Plugin using which I was able to setup Google Authentication on my site.


Here's what we need to enable Google 2FA:

1) A description of your site

2) A 16 character long alpanumeric string (M343ZCYUEZY7OJ6P)- This string needs to be retained for authentication


Here's the script to generate the QR code

<img id=GA_QRCODE src="">


var chl=escape("otpauth://totp/";

qrcodeurl="|0&chl=" chl;




The above code will display a 300 by 300 pixel QR code on the page. Download the Google Authenticator app on your smartphone and scan the code


The next step is to setup user authentication and validate it against Google. 

We  need the base32.php file to convert the secret key before sending it to Google. When the code is entered the following code will be executed:


/*Note: $userEnteredValue is the current code entered by the user*/


if(strlen($userEnteredValue) != 6)


echo "Invalid Auth Code";




$tm = floor( time() / 30 );


$firstcount = 0;

$lastcount  =  3;

$isg2fa = "0";

/* Keys from 30 seconds before and after are valid as well.*/

for ($i=$firstcount; $i<$lastcount; $i ) 


/* Pack time into binary string*/

$time=chr(0).chr(0).chr(0).chr(0).pack('N*',$tm $i);

/* Hash it with users secret key*/

$hm = hash_hmac( 'SHA1', $time, $secretkey, true );

/*// Use last nipple of result as index/offset*/

$offset = ord(substr($hm,-1)) & 0x0F;

/*grab 4 bytes of the result*/


/* Unpak binary value*/



/* Only 32 bits*/

$value = $value & 0x7FFFFFFF;

$value = $value % 1000000;

if($value == $userEnteredValue)


$isg2fa ;


if($isg2fa > 1)


echo "Authorized";




echo "Invalid Auth Code";


That's all to add an extra layer of security on your site.