Home > Dev > PHP Security > Two-Factor Authentication (2FA)

Two-Factor Authentication (2FA)

This code adds a basic two-factor authentication mechanism.

session_start();
require 'vendor/autoload.php';
use OTPHP\TOTP;

function generate_2fa_secret() {
    $totp = TOTP::create();
    $_SESSION['2fa_secret'] = $totp->getSecret();
    return $totp->getProvisioningUri();
}

function verify_2fa_token($token) {
    $totp = TOTP::create($_SESSION['2fa_secret']);
    return $totp->verify($token);
}

// Usage example
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['2fa_token']) && verify_2fa_token($_POST['2fa_token'])) {
        echo '2FA verified';
    } else {
        echo 'Invalid 2FA token';
    }
} else {
    $provisioning_uri = generate_2fa_secret();
    echo '<img src="https://api.qrserver.com/v1/create-qr-code/?data=' . urlencode($provisioning_uri) . '">';
}
Back