As online security threats continue to evolve, implementing Two-Factor Authentication (2FA) in your PHP applications has become essential. 2FA adds an extra layer of protection on top of the traditional username and password by requiring a second factor — usually a code sent to a user’s phone or generated by an app like Google Authenticator.
🔧 Prerequisites
- Basic PHP knowledge
- Composer installed
- Access to a PHP development environment
📦 Step 1: Install the Google Authenticator Library
We’ll use robthree/twofactorauth
, a popular PHP package for 2FA.
composer require robthree/twofactorauth
🛠 Step 2: Generate and Store the Secret Key
Each user will need a unique secret key. Store this key securely in your database.
require 'vendor/autoload.php';
use RobThree\Auth\TwoFactorAuth;
$tfa = new TwoFactorAuth('MyApp');
// Generate a new secret for the user
$secret = $tfa->createSecret();
// Store $secret in the user's database record
📱 Step 3: Show QR Code for User Setup
Let the user scan a QR code with Google Authenticator or a similar app:
$label = 'user@example.com';
$qrCodeUrl = $tfa->getQRCodeImageAsDataUri($label, $secret);
// Embed the image in your HTML
echo '<img src="' . $qrCodeUrl . '" />';
🔐 Step 4: Verify the User's 2FA Code
When a user logs in, prompt for their 2FA code and verify it:
$userCode = $_POST['2fa_code']; // from user input
$isValid = $tfa->verifyCode($secret, $userCode);
if ($isValid) {
echo "2FA verified!";
} else {
echo "Invalid 2FA code.";
}
💡 Bonus Tips
- Allow users to regenerate or reset their 2FA secret in case they lose access.
- Use HTTPS to prevent man-in-the-middle attacks.
- Implement rate limiting on 2FA code verification to deter brute-force attempts.
✅ Conclusion
Implementing 2FA in PHP using robthree/twofactorauth
is a straightforward way to significantly improve your application's security. With just a few steps, you can protect your users and their data from unauthorized access.
Secure your app — one factor at a time.