1. Go to this page and download the library: Download ndtan/php-2fa 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/ */
ndtan / php-2fa example snippets
use ndtan\TwoFA\Totp\Totp;
use ndtan\TwoFA\QR\EndroidQrProvider;
// 1) Generate a Base32 secret
$secret = Totp::generateSecret(); // e.g. "JBSWY3DPEHPK3PXP..."
// 2) Build otpauth URI
$uri = Totp::buildOtpAuthUri('[email protected]', 'MyApp', $secret);
// 3) Render QR (SVG Data URI)
$qr = (new EndroidQrProvider())->render($uri, 256, true); // "data:image/svg+xml;base64,..."
// 4) Verify user input (±1 step = ±30s window)
$result = Totp::verify($secret, $userInputCode, period: 30, digits: 6, algo: 'sha1', window: 1);
if ($result['valid']) {
// success
}
use ndtan\TwoFA\Backup\BackupCodes;
// Generate one-time backup codes for the user
$codes = BackupCodes::generate(count: 10, length: 10);
// Store **hashes** only
$hashes = array_map(fn($c) => BackupCodes::hash($c), $codes);
// Verify later
$isValid = BackupCodes::verify($inputBackupCode, $storedHash);
$qrDataUri = (new EndroidQrProvider())->render($otpauthUri); // data:image/svg+xml;base64,...
// HTML
// <img src="<?= htmlspecialchars($qrDataUri, ENT_QUOTES)
// Alias 'ndt.2fa' is auto-registered by the ServiceProvider
Route::middleware('ndt.2fa')->group(function () {
Route::get('/dashboard', DashboardController::class);
});
use ndtan\TwoFA\Security\Stores\ArrayRateStore;
use ndtan\TwoFA\Security\Stores\ArrayUsedCodeStore;
use ndtan\TwoFA\Security\AttemptLimiter;
use ndtan\TwoFA\Security\Verifier;
$limiter = new AttemptLimiter(new ArrayRateStore(), maxAttempts: 5, perSeconds: 300, lockoutSeconds: 300);
$used = new ArrayUsedCodeStore();
$verifier = new Verifier($limiter, $used); // defaults: period=30, digits=6, algo='sha1', window=1
$res = $verifier->verifyTotp('user:42', $secret, $userCode);
switch ($res['status']) {
case 'ok': /* mark session verified */ break;
case 'rate_limited':/* advise retry in $res['retry_after'] seconds */ break;
case 'replayed': /* code already used in current period */ break;
default: /* invalid: $res['remaining'] attempts left */ break;
}
$cache = /* any PSR-16 CacheInterface implementation */;
$limiter = new AttemptLimiter(new \ndtan\TwoFA\Security\Stores\Psr16RateStore($cache));