PHPackages                             ez-php/two-factor - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. ez-php/two-factor

ActiveLibrary[Framework](/categories/framework)

ez-php/two-factor
=================

Two-factor authentication module for the ez-php framework — RFC 6238 TOTP, QR code URLs, backup codes, and HTTP middleware

1.3.0(1mo ago)00MITPHPPHP ^8.5CI passing

Since Mar 29Pushed 1mo agoCompare

[ Source](https://github.com/ez-php/two-factor)[ Packagist](https://packagist.org/packages/ez-php/two-factor)[ Docs](https://github.com/ez-php/two-factor)[ RSS](/packages/ez-php-two-factor/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (9)Versions (4)Used By (0)

ez-php/two-factor
=================

[](#ez-phptwo-factor)

Two-factor authentication module for the ez-php framework. Provides RFC 6238 TOTP (Time-based One-Time Password) support with pure PHP — no external SDK required. Includes secret generation, QR code URL generation, code verification, backup codes, and HTTP middleware.

Installation
------------

[](#installation)

```
composer require ez-php/two-factor
```

Setup
-----

[](#setup)

### 1. Implement the interface on your user model

[](#1-implement-the-interface-on-your-user-model)

```
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
}
```

### 2. Register the service provider

[](#2-register-the-service-provider)

In `provider/modules.php`:

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

### 3. Add the middleware

[](#3-add-the-middleware)

Apply `TwoFactorMiddleware` to routes that require 2FA verification:

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

Usage
-----

[](#usage)

### Enabling 2FA for a user

[](#enabling-2fa-for-a-user)

```
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
```

### Verifying the setup code

[](#verifying-the-setup-code)

```
// 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]);
}
```

### Verifying during login

[](#verifying-during-login)

After the user is authenticated, mark the session as verified:

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

### Backup codes

[](#backup-codes)

```
// 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;
    }
}
```

Middleware Behaviour
--------------------

[](#middleware-behaviour)

`TwoFactorMiddleware` runs on every request passing through it:

ConditionResultNo authenticated userPass through (200)User does not implement `TwoFactorAuthenticableInterface`Pass through (200)User has 2FA disabledPass through (200)Session contains `two_factor_verified = true`Pass through (200)2FA required but not verified`423 Locked` + `X-Requires-2FA: true`The `X-Requires-2FA: true` header signals to API clients that a 2FA verification step is needed.

API Reference
-------------

[](#api-reference)

### `TwoFactorManager`

[](#twofactormanager)

MethodDescription`generateSecret(): string`Generates a 16-character Base32 secret (80 bits of entropy)`generateCode(string $secret, ?int $timestamp = null): string`Generates a 6-digit TOTP code`verifyCode(string $secret, string $code, ?int $timestamp = null): bool`Verifies a code with ±1 time step tolerance`getQrCodeUrl(string $issuer, string $account, string $secret): string`Returns an `otpauth://totp/...` URI for QR code generation`generateBackupCodes(int $count = 8): string[]`Generates `XXXX-XXXX` format backup codes`hashBackupCode(string $code): string`Bcrypt-hashes a backup code for storage`verifyBackupCode(string $code, string $hash): bool`Verifies a backup code against its hash### `TwoFactorMiddleware`

[](#twofactormiddleware)

ConstantValue`SESSION_KEY``'two_factor_verified'`Standards Compliance
--------------------

[](#standards-compliance)

- **RFC 6238** — TOTP: Time-Based One-Time Password Algorithm
- **RFC 4226** — HOTP: HMAC-Based One-Time Password Algorithm
- **RFC 4648** — Base32 encoding/decoding

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance90

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a15a63c46d239d42b8ed4c2fe9adbc5fe99eb62f6e5bb90f08021e0c068e8b37?d=identicon)[AU9500](/maintainers/AU9500)

---

Top Contributors

[![AU9500](https://avatars.githubusercontent.com/u/122030400?v=4)](https://github.com/AU9500 "AU9500 (6 commits)")

---

Tags

phpframeworkotptotpsecurityAuthentication2fatwo-factorez-php

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ez-php-two-factor/health.svg)

```
[![Health](https://phpackages.com/badges/ez-php-two-factor/health.svg)](https://phpackages.com/packages/ez-php-two-factor)
```

###  Alternatives

[remotemerge/totp-php

Lightweight, fast, and secure TOTP (2FA) authentication library for PHP — battle tested, dependency free, and ready for enterprise integration.

2010.2k](/packages/remotemerge-totp-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
