PHPackages                             phputil/csrf - 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. phputil/csrf

ActiveLibrary

phputil/csrf
============

CSRF middleware for phputil/router

v0.2.3(10mo ago)119MITPHP

Since Jul 9Pushed 10mo ago1 watchersCompare

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

READMEChangelogDependencies (7)Versions (7)Used By (0)

phputil-csrf
============

[](#phputil-csrf)

> 🔌 CSRF middleware for [phputil/router](https://github.com/thiagodp/router)

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

[](#installation)

> Requires phputil/router **v0.2.14+**

```
composer require phputil/csrf
```

Usage
-----

[](#usage)

### With default options

[](#with-default-options)

```
require_once 'vendor/autoload.php';
use phputil\router\Router;
use function phputil\crsf\crsf; // Step 1: Declare the namespace usage for the function.
$app = new Router();

$app->use( crsf() ); // Step 2: Invoke the function to use it as a middleware.

$app->get( '/', function( $req, $res ) {
    $res->send( 'Hello' );
} );
$app->listen();
```

Documentation
-------------

[](#documentation)

```
/**
 * Returns a CSRF middleware.
 *
 * @param array|CsrfOptions $options CSRF options.
 * @param CsrfStrategy $strategy Strategy. By default it uses a cookie-based strategy with default options.
 * @param CsrfStorage $storage Storage. By default it uses a session-based storage with default options.
 *
 * @return callable
 */
function csrf( $options = [], CsrfStrategy $strategy = null, CsrfStorage $storage = null ): callable;
```

Argument `$options` (array, default `[]`) can have the following keys:

- `disableTokenMasking` (bool, default `false`) indicates if token masking should be disabled.
    - Note: By default, the randomly-generated token is masked through a XOR operation with a random key and then converted to base64.
- `disableTokenRenewal` (bool, default `false`) indicates if token renewal should be disabled.
- `tokenLength` (int, default `20`) indicates the desired token length. Note that this is the **unmasked** token length.

### Available Strategies

[](#available-strategies)

The following classes are available:

- `CookieBasedCsrfStrategy`: uses cookies to send and receive the CSRF token. That's the default strategy.
    - Its constructor receives two arguments, both optional:
        - `$strategyOptions` (array, default `[]`) that can have:
            - `"cookieName"`: the name of the CSRF cookie. By default, it is `csrf_token`.
        - `$cookieOptions` (array, default `[]`) that can have the same options as PHP's [setcookie()](https://www.php.net/manual/en/function.setcookie).
- `HeaderBasedCsrfStrategy`: uses HTTP headers to send and receive the CSRF token.
    - Its constructor receives one argument, `$strategyOptions` (array, default `[]`), that is optional and can have:
        - `"requestHeaderName"`: expected request header. By default it is `"X-CSRF-Token"`.
        - `"responseHeaderName"`: produced response header. By default it is `"CSRF-Token"`.

**Note**: You can create your own CSRF strategy by implementing the interface `CsrfStrategy`.

### Available Storages

[](#available-storages)

The following classes are available:

- `InSessionCsrfStorage`: uses PHP's `$_SESSION` to store the CSRF token in order to compare it later.
    - Its constructor receives one optional argument, `$sessionKey` (string), which is the key stored in the `$_SESSION` variable. By default it is `csrf`.

**Note**: You can create your own CSRF storage by implementing the interface `CsrfStorage`.

License
-------

[](#license)

[MIT](LICENSE) © [Thiago Delgado Pinto](https://github.com/thiagodp)

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance54

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

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

Recently: every ~91 days

Total

6

Last Release

312d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/154324d722a6ee9c252a0338329781084a97af2d0ea9faaf39176df5a689a2ec?d=identicon)[thiagodp](/maintainers/thiagodp)

---

Top Contributors

[![thiagodp](https://avatars.githubusercontent.com/u/2997844?v=4)](https://github.com/thiagodp "thiagodp (9 commits)")

###  Code Quality

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

PHPackages © 2026

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