PHPackages                             rafalmasiarek/csrf-token - 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. [Security](/categories/security)
4. /
5. rafalmasiarek/csrf-token

ActiveLibrary[Security](/categories/security)

rafalmasiarek/csrf-token
========================

Encrypted CSRF token library with fingerprint and caching (file, MySQL, Redis)

v1.3.3(5mo ago)017[2 issues](https://github.com/rafalmasiarek/php-csrf/issues)MITPHPPHP &gt;=7.4CI passing

Since Jul 10Pushed 5mo agoCompare

[ Source](https://github.com/rafalmasiarek/php-csrf)[ Packagist](https://packagist.org/packages/rafalmasiarek/csrf-token)[ RSS](/packages/rafalmasiarek-csrf-token/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (2)Versions (12)Used By (0)

PHP CSRF — Encrypted, Container‑Aware Tokens
============================================

[](#php-csrf--encrypted-containeraware-tokens)

A secure CSRF protection library with **AES‑256‑GCM** encryption and **per‑form containers**. Each form (container) has its own session bucket, derived key (HKDF) and optional pepper. Tokens are bound to container id, client IP and User‑Agent (both configurable).

Features
--------

[](#features)

- Stateless encrypted token (payload: token, ip, ua, iat, container id)
- AES‑256‑GCM with IV + auth tag, AAD binds to container id/prefix
- Per‑container isolation: replay across forms is impossible
- Configurable bindings (IP/UA) per container
- TTL support (set `0` to disable expiry — not recommended)
- Optional cache layer (File / MySQL / Redis) for fast‑path validation
- Backwards compatible API: `generate()`/`validate()` still work for the `"default"` container

Install
-------

[](#install)

```
composer require rafalmasiarek/php-csrf
```

Quick Start
-----------

[](#quick-start)

```
use rafalmasiarek\Csrf\Csrf;

session_start();

$csrf = new Csrf($masterKey32Bytes, 900); // TTL=900s
$token = $csrf->generate();               // default container
//
```

Validation:

```
if (!$csrf->validate($_POST['_csrf'] ?? null)) {
    http_response_code(419);
    exit('CSRF verification failed');
}
```

Containers (Multiple Forms)
---------------------------

[](#containers-multiple-forms)

```
use rafalmasiarek\Csrf\{Csrf, CsrfCacheWrapper, FileStorage};

$csrf = (new Csrf($masterKey32Bytes, 900))
    ->withContainer('signup', ['prefix' => 'auth_', 'bind_ip' => true,  'bind_ua' => true])
    ->withContainer('profile', ['prefix' => 'user_', 'bind_ip' => false, 'bind_ua' => true]);

$cache = new FileStorage(__DIR__ . '/var/csrf-cache'); // or MysqlStorage / RedisStorage
$csrfCached = new CsrfCacheWrapper($csrf, $cache);

// View:
$tokenSignup = $csrfCached->generateFor('signup');
$tokenProfile = $csrfCached->generateFor('profile');

// POST handler:
$ok = $csrfCached->validateFor('signup', $_POST['_csrf'] ?? '');
```

Storage Options
---------------

[](#storage-options)

- `FileStorage($dir)` — writes JSON files (hashed filenames)
- `MysqlStorage(PDO $pdo)` — uses table `csrf_cache(token_hash, payload JSON, created_at)`
- `RedisStorage(Redis $redis, string $prefix = 'csrf:', int $ttl = 900)`

> Storage keys are hashed; for multi‑containers we pass a composite `"|"` to avoid collisions.

Security Notes
--------------

[](#security-notes)

- Keep the **master key** (32 bytes) secret. Rotate periodically.
- Prefer enabling **IP/UA binding**. Disable only if your environment makes them unstable.
- Set a **reasonable TTL**. `0` (no expiry) is supported but not recommended.
- Tokens are **burned after successful validation** (per container).

---

Client Context Provider (IP / User-Agent injection)
---------------------------------------------------

[](#client-context-provider-ip--user-agent-injection)

Since version **1.3.2** the library supports **external injection of client IP and User-Agent**, instead of relying solely on `$_SERVER`.

### Passing IP/UA explicitly

[](#passing-ipua-explicitly)

```
$token = $csrf->generate($realIp, $realUa);
$isValid = $csrf->validate($submittedToken, $realIp, $realUa);
```

Container-specific:

```
$token = $csrf->generateFor('signup', $realIp, $realUa);
$ok = $csrf->validateFor('signup', $submittedToken, $realIp, $realUa);
```

### ClientContextProviderInterface

[](#clientcontextproviderinterface)

```
use rafalmasiarek\Csrf\ClientContextProviderInterface;

class SlimRequestProvider implements ClientContextProviderInterface {
    public function __construct(private \Psr\Http\Message\ServerRequestInterface $request) {}

    public function getIp(): string {
        return $this->request->getAttribute('client_ip') ?? '';
    }

    public function getUserAgent(): string {
        return $this->request->getHeaderLine('User-Agent');
    }
}
```

Usage:

```
$csrf = new Csrf($key, 900, new SlimRequestProvider($request));
```

---

Migration
---------

[](#migration)

### From 1.2.1 → 1.3.x

[](#from-121--13x)

- **What changed**: The library is now **container‑aware**. Internal session storage moved under `$_SESSION['_csrf_v2'][]` and tokens are bound to container id via AAD and payload.
- **Backwards compatibility**: Existing calls to `generate()` / `validate()` continue to work for the implicit `"default"` container.
- **Recommended**: Start calling `generateFor('')` / `validateFor('', $token)` for each separate form.

### From 1.0.0 → 1.1.x

[](#from-100--11x)

- Namespace unified under `rafalmasiarek\Csrf` and PSR‑4 autoloading.

Examples
--------

[](#examples)

See [`example/`](example/) for drop‑in snippets:

- `basic/index.php`
- `containers/index.php`
- `fileCache/index.php`
- `ipOverride/index.php`
- `mysql/schema.sql`

View Helpers
------------

[](#view-helpers)

### Plates (League\\Plates)

[](#plates-leagueplates)

```
use League\Plates\Engine;
use rafalmasiarek\Csrf\Csrf;
use rafalmasiarek\Csrf\Helpers\Plates\CsrfExtension;

$view = new Engine(__DIR__.'/views');
$csrf = new Csrf($masterKey, 900);
CsrfExtension::register($view, $csrf);

// In template:
```

### Twig

[](#twig)

```
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use rafalmasiarek\Csrf\Csrf;
use rafalmasiarek\Csrf\Helpers\Twig\CsrfExtension;

$twig = new Environment(new FilesystemLoader(__DIR__.'/views'));
$csrf = new Csrf($masterKey, 900);
$twig->addExtension(new CsrfExtension($csrf));

// In template: {{ csrf_field('signup')|raw }}
```

### Blade (Laravel)

[](#blade-laravel)

```
use Illuminate\View\Compilers\BladeCompiler;
use rafalmasiarek\Csrf\Csrf;
use rafalmasiarek\Csrf\Helpers\Blade\CsrfBlade;

// In a service provider boot():
CsrfBlade::register($this->app->make(BladeCompiler::class), app(Csrf::class));

// In Blade: @csrfField('signup')
```

License
-------

[](#license)

MIT

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance75

Regular maintenance activity

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

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 ~22 days

Total

7

Last Release

167d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/17765d36dfdee9f4179c94861184464cb4282d224e9db7fa86b4dff6005c166c?d=identicon)[rafalmasiarek](/maintainers/rafalmasiarek)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/rafalmasiarek-csrf-token/health.svg)

```
[![Health](https://phpackages.com/badges/rafalmasiarek-csrf-token/health.svg)](https://phpackages.com/packages/rafalmasiarek-csrf-token)
```

###  Alternatives

[defuse/php-encryption

Secure PHP Encryption Library

3.9k162.4M212](/packages/defuse-php-encryption)[roave/security-advisories

Prevents installation of composer packages with known security vulnerabilities: no API, simply require it

2.9k97.3M6.4k](/packages/roave-security-advisories)[mews/purifier

Laravel 5/6/7/8/9/10 HtmlPurifier Package

2.0k16.7M112](/packages/mews-purifier)[robrichards/xmlseclibs

A PHP library for XML Security

41278.1M118](/packages/robrichards-xmlseclibs)[bjeavons/zxcvbn-php

Realistic password strength estimation PHP library based on Zxcvbn JS

86917.5M63](/packages/bjeavons-zxcvbn-php)[enlightn/security-checker

A PHP dependency vulnerabilities scanner based on the Security Advisories Database.

33732.2M110](/packages/enlightn-security-checker)

PHPackages © 2026

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