A Step-by-Step Guide to Adding Google Two-Factor Authentication (2FA) to Your Website Using PHP

Photo by Franck on Unsplash

A Step-by-Step Guide to Adding Google Two-Factor Authentication (2FA) to Your Website Using PHP

Table of contents

No heading

No headings in the article.

In an increasingly digital world, ensuring the security of your users' accounts is of utmost importance. Two-Factor Authentication (2FA) adds an additional layer of security by requiring users to provide two different authentication factors. Google's 2FA is a popular and trusted choice. In this guide, we'll walk you through the process of adding Google 2FA to your website using PHP.


  • A basic understanding of HTML, PHP, and web development.

  • Access to a web server for hosting your PHP code.

  • Composer installed on your server to manage PHP packages.

Step 1: Set Up Your Development Environment

Before you begin, make sure you have a development environment ready:

  1. Web Server: Set up a web server, such as Apache or Nginx, to host your PHP application.

  2. Composer: Install Composer, the PHP dependency manager, on your server. You can download it from getcomposer.org.

Step 2: Install the Required Package

To implement Google 2FA in your PHP application, you'll need to use a PHP library. The PHPGangsta/GoogleAuthenticator library is a reliable choice. To install it:

  1. Open your command line interface.

  2. Navigate to your project directory.

  3. Run the following command to install the library using Composer:

     composer require php-gangsta/google-authenticator

Step 3: Create a New PHP File for 2FA Setup

Now, create a new PHP file, e.g., enable-2fa.php, where users can enable 2FA for their accounts.

  1. Add the necessary PHP code at the beginning of the file to initialize the Google Authenticator:

     require 'vendor/autoload.php';
     use PHPGangsta_GoogleAuthenticator;
     // Initialize the Google Authenticator
     $ga = new PHPGangsta_GoogleAuthenticator();
     // Other initialization code
     // ...

Step 4: Generate Secret Keys and QR Codes

In the enable-2fa.php file, you'll generate secret keys and QR codes for users to set up 2FA. Use the following code:

// Generate a secret key for the user
$secret = $ga->createSecret();

// Generate a QR code URL for the user to scan with Google Authenticator app
$qrCodeUrl = $ga->getQRCodeGoogleUrl('YourAppTitle', $secret);

This code generates a unique secret for each user and a QR code URL to add your website to their Google Authenticator app.

Step 5: Display QR Code to the User

In your HTML, display the generated QR code to the user:

<img src="<?php echo $qrCodeUrl; ?>" alt="QR Code for Google Authenticator">

This QR code is what the user will scan with their Google Authenticator app.

Step 6: Create a Form for Verification

Below the QR code, create an HTML form that allows users to enter the verification code they receive from the app:

<form action="enable-2fa.php" method="post">
    <label for="verification_code">Enter the code from the app:</label>
    <input type="text" id="verification_code" name="verification_code" required>
    <button type="submit">Enable 2FA</button>

Step 7: Verify the User's Code

In the PHP section, verify the code entered by the user:

    $userCode = $_POST['verification_code'];

    // Verify the code entered by the user
    $isValid = $ga->verifyCode($secret, $userCode);

    if ($isValid) {
        // Code is valid - perform actions like enabling 2FA, storing the secret key, and redirecting

        // Example: Store the secret key in your database
        $insert = "INSERT INTO user_2fa (user_id, secret_key) VALUES ('$user_id', '$secret')";
        mysqli_query($link, $insert); // Replace with your database logic

        // Redirect to a success page
        header("Location: success.php");
        exit; // Stop script execution
    } else {
        $code_err = 'Invalid Code.';

This code verifies the user's input, and if the code is valid, it stores the secret key in your database.

Step 8: Secure User Accounts

With 2FA enabled, your website adds an extra layer of security. Users can now use their Google Authenticator app to generate a 2FA code during login or sensitive operations, making it significantly harder for unauthorized access.

Conclusion: Implementing Google 2FA in your PHP application enhances security by adding a second layer of protection for user accounts. Users can enable 2FA easily by scanning a QR code with the Google Authenticator app. Make sure to handle secret key storage and database integration securely for a robust 2FA implementation.