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

ActiveLibrary[Security](/categories/security)

linna/csrf-guard
================

Linna Cross-site request forgery Guard

v2.0.0(3y ago)51104[2 PRs](https://github.com/linna/csrf-guard/pulls)MITPHPPHP &gt;=8.1CI failing

Since Jul 26Pushed 3y ago2 watchersCompare

[ Source](https://github.com/linna/csrf-guard)[ Packagist](https://packagist.org/packages/linna/csrf-guard)[ Docs](https://github.com/linna/csrf-guard)[ RSS](/packages/linna-csrf-guard/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (10)Dependencies (3)Versions (16)Used By (0)

 [![Linna Logo](logo-linna-128.png)](#)

 [![Linna framework Logo](logo-csrf.png)](#)

[![Tests](https://github.com/linna/csrf-guard/workflows/Tests/badge.svg)](https://github.com/linna/csrf-guard/actions)[![Quality Gate Status](https://camo.githubusercontent.com/014c18258e06389fc31375ddbaf328f6e057216ba81a8ef70c181a97a3231c65/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d6c696e6e615f637372662d6775617264266d65747269633d616c6572745f737461747573)](https://sonarcloud.io/summary/new_code?id=linna_csrf-guard)[![PDS Skeleton](https://camo.githubusercontent.com/3c7140ee36205075ed977142f25c29eb1fb7809e9b86a865461fc21776ad1665/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7064732d736b656c65746f6e2d626c75652e7376673f7374796c653d666c6174)](https://github.com/php-pds/skeleton)[![PHP 8.1](https://camo.githubusercontent.com/1c708345a94c698fd596459da39a9535062cfa1162a57a8ae4e3cdd54e00a25d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312d3838393242462e737667)](http://php.net)

About
=====

[](#about)

Provide a class for generate and validate tokens utilized against [Cross-site Request Forgery](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)).

> **Note:** Don't consider this class a definitive method to protect your web site/application. If you wish deepen how to prevent csrf you can start [here](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet)

Requirements
============

[](#requirements)

This package require

- php 7.0 until version v1.1.2
- php 7.1 from v1.2.0
- php 7.4 from v1.4.0
- php 8.1 from v2.0.0

Installation
============

[](#installation)

With composer:

```
composer require linna/csrf-guard

```

Token types
===========

[](#token-types)

> **Note:** Storage it's intended that the data about token or the token is stored in session.

The package provides three types of token:

- Encryption-based CSRF token
- HMAC-based CSRF token
- Synchronizer CSRF token

Encryption-based token
----------------------

[](#encryption-based-token)

Encryption-based CSRF token is a token that is the result of a cryptographic algorithm, some data is encrypted using a secret key only known from the server .The implementation in this library uses `libsodium` aead contruction `XChaCha20-Poly1305`. The token has expire time and require local storage.

The token security depends from:

- secret key storage
- strength of `XChaCha20-Poly1305`

This token is valid until validated or until it expires. It's possible to select a length of the token. The length of the token doesn't affect the storage used.

The key used for the engryption is generated for every session, the nonce for every token.

HMAC-based token
----------------

[](#hmac-based-token)

HMAC-based CSRF token is a token that is computed by applying an HMAC function to some data and a secret key that is only known from the server. The implementation in this library uses php `hash_hmac` with the `sha3-384` algorithm. This type of token deosn't require local storage and it has an expire time.

The token security depends from:

- secret key storage
- strength of `sha3-384`

This token is valid until expires and can be validate more times. Also has fixed length and it's not possible to change it to obtain a shorter or longer token.

The key used to authenticate is fully managed by the user of the library.

Synchronizer token
------------------

[](#synchronizer-token)

The Synchronizer CSRF token is a token randomly generated. This library uses php `random_bytes`. The token has expire time and require local storage.

The token security depends from:

- the length of the token

This token is valid until validated or until it expires. It's possible to select a length of the token. The length of the token affects the storage used.

Usage
=====

[](#usage)

> **Note:** Session must be started before you create the instance of a provider, if no a `SessionNotStartedException` will be throw, this is not true if you use the `HmacTokenProvider`.

Get started
-----------

[](#get-started)

How to get and validate a token using few lines of code.

### Generate a provider

[](#generate-a-provider)

```
//start the session
\session_start();

//generate token provider
$provider = ProviderSimpleFactory::getProvider();
```

### Get a token

[](#get-a-token)

```
//previous php code

//get a token from provider
$token = $provider->getToken();
```

### Validate it

[](#validate-it)

```
//previous php code

//true if valid, false otherwise
$isValid = $provider->validate($token);
```

Provider configuration
----------------------

[](#provider-configuration)

The `ProviderSimpleFactory::getProvider()` static method has two parameters:

- the provider
- options for the provider

### EncryptionTokenProvider config

[](#encryptiontokenprovider-config)

OptionsDefault ValueUnityRangeMandatoryexpire600seconds0-86400nostorageSize10tokens2-64notokenLength16bytes16-128noExample of usage:

```
//start the session
\session_start();

//get specific encryption token provider
$provider = ProviderSimpleFactory::getProvider(
    provider: EncryptionTokenProvider::class, // specific token provider
    options: [                                // options
        'expire' => 3600,                     // token expire in 3600 seconds, 1 hour
        'storageSize' => 16,                  // provider can store maximum 1 key and 16 nonces per session,
        'tokenLength' => 16                   // desidered token length in bytes, token will be used as plaintext and not stored
    ]
);
```

### HmacTokenProvider config

[](#hmactokenprovider-config)

OptionsDefault ValueUnityRangeMandatoryvalue//yeskey//yesexpire600seconds0-86400noExample of usage:

```
//get specific hmac token provider
$provider = ProviderSimpleFactory::getProvider(
    provider: HmacTokenProvider::class,             // specific token provider
    options: [                                      // options
        'value' => 'value will be hashed in token', // value will be hashed in token
        'key' => 'key_to_authenticate'              // key to authenticate the hash
    ]
);
```

### SynchronizerTokenProvider config

[](#synchronizertokenprovider-config)

OptionsDefault ValueUnityRangeMandatoryexpire600seconds0-86400nostorageSize10tokens2-64notokenLength32bytes16-128noExample of usage:

```
//start the session
\session_start();

//get specific syncronizer token provider
$provider = ProviderSimpleFactory::getProvider(
    provider: SynchronizerTokenProvider::class, // specific token provider
    options: [                                  // options
        'expire' => 3600,                       // token expire in 3600 seconds, 1 hour
        'storageSize' => 16,                    // provider can store maximum 16 token per session,
        'tokenLength' => 32                     // desidered token length in bytes, token will be the double in chars
    ]
);
```

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 98.5% 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 ~225 days

Recently: every ~407 days

Total

10

Last Release

1187d ago

Major Versions

v1.4.0 → v2.0.02023-02-11

PHP version history (4 changes)v1.0.0PHP ^7.0.0

v1.2.0PHP ^7.1

v1.4.0PHP &gt;=7.4

v2.0.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/3b0180939371d6dbe2ab2d18829614d90a995b833d6bb7f503a11766f8d130f0?d=identicon)[s3b4stian](/maintainers/s3b4stian)

---

Top Contributors

[![s3b4stian](https://avatars.githubusercontent.com/u/11441761?v=4)](https://github.com/s3b4stian "s3b4stian (130 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (2 commits)")

---

Tags

csrfcsrf-protectioncsrf-tokensphpcsrfsurfcsrf-guard

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

PHPackages © 2026

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