PHP code example of ez-php / two-factor

1. Go to this page and download the library: Download ez-php/two-factor library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ez-php / two-factor example snippets


use EzPhp\Auth\UserInterface;
use EzPhp\TwoFactor\TwoFactorAuthenticableInterface;

final class User implements UserInterface, TwoFactorAuthenticableInterface
{
    public function hasTwoFactorEnabled(): bool
    {
        return (bool) $this->two_factor_enabled;
    }

    public function getTwoFactorSecret(): string
    {
        return $this->two_factor_secret;
    }

    // ... UserInterface methods
}

$app->register(\EzPhp\TwoFactor\TwoFactorServiceProvider::class);

// routes/web.php
$router->group(['middleware' => [TwoFactorMiddleware::class]], function ($router) {
    $router->get('/dashboard', [DashboardController::class, 'index']);
});

use EzPhp\TwoFactor\TwoFactorManager;

$manager = $container->make(TwoFactorManager::class);

// Generate and store the secret
$secret = $manager->generateSecret();
// → store $secret in your user record (two_factor_secret column)

// Get QR code URL to display to the user
$qrUrl = $manager->getQrCodeUrl('MyApp', $user->email, $secret);
// → render into a QR code image using your preferred library

// User scans QR code and enters the first code from their app
if ($manager->verifyCode($secret, $request->input('code'))) {
    // Enable 2FA for the user
    $user->update(['two_factor_enabled' => true, 'two_factor_secret' => $secret]);
}

// In your 2FA verification controller
if ($manager->verifyCode(Auth::user()->getTwoFactorSecret(), $request->input('code'))) {
    $_SESSION[TwoFactorMiddleware::SESSION_KEY] = true;
    return redirect('/dashboard');
}

// Generate backup codes (store hashes, show plain codes to user once)
$codes = $manager->generateBackupCodes(8);
foreach ($codes as $code) {
    $hashes[] = $manager->hashBackupCode($code);
}
// Store $hashes in the database

// Verify a backup code on login
foreach ($storedHashes as $hash) {
    if ($manager->verifyBackupCode($inputCode, $hash)) {
        // Valid — invalidate this backup code
        break;
    }
}