two-factor authentication in PHP, I will use packagist.org/packages/pragmarx/google2fa for this tutorial


Steps

First we need to install the package, which is as easy as using composer:

composer require pragmarx/google2fa


Then, we can generate a secret for our user(s).

<?php

# Include packages
require_once(__DIR__ . '/vendor/autoload.php');

# Create the 2FA class
$google2fa = new PragmaRX\Google2FA\Google2FA();
$userSecret = $google2fa->generateSecretKey();

print "Please enter the following secret into your phone:" . PHP_EOL .  $userSecret . PHP_EOL;

Now, you have a secret for our users, they can provide it into their Google authenticator application.


Now when that user wishes to authenticate, the application needs to do the following:

<?php

# Include packages
require_once(__DIR__ . '/vendor/autoload.php');

# Create the 2FA class
$google2fa = new PragmaRX\Google2FA\Google2FA();
print "Please enter your 2FA code:" . PHP_EOL;
$code = readline();

# Fetch/load the user secret in whatever way you do.
$userSecret = fetchUserSecretFromPersistenceStore();
$valid = $google2fa->verifyKey($userSecret, $code); 

print ($valid) ? "Authenication PASSED!": "Authentication FAILED!";
print PHP_EOL;


Install Package QR Codes

install our QR code generator package.

composer require bacon/bacon-qr-code

Generate QR Codes

<?php

# Include packages
require_once(__DIR__ . '/vendor/autoload.php');

# Create the 2FA class
$google2fa = new PragmaRX\Google2FA\Google2FA();

$title = "blog.programster.org";
$usernameOrEmail = "admin@programster.org";
$userSecret = fetchUserSecretFromPersistenceStore();

$qrCodeData = $google2fa->getQRCodeUrl(
    $title,
    $usernameOrEmail,
    $userSecret
);

print "QR code url is: $qrCodeUrl" . PHP_EOL;

# Now create the QR code image from the URL.
$renderer = new \BaconQrCode\Renderer\ImageRenderer(
    new \BaconQrCode\Renderer\RendererStyle\RendererStyle(400),
    new \BaconQrCode\Renderer\Image\ImagickImageBackEnd()
);

$writer = new BaconQrCode\Writer($renderer);
$writer->writeFile($qrCodeData, 'qrcode.png');

print "Please open qrcode.png and scan it with your google authenticator app." . PHP_EOL;

Then you just need to make sure to install the php8.0-imagick package

Thanks