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

ActiveLibrary[Security](/categories/security)

itrack/csrf
===========

Easy to use cross site request forgery protection.

1.1(6y ago)014.9k↓50%2PHPPHP &gt;=7.0.0

Since Nov 13Pushed 6y agoCompare

[ Source](https://github.com/itrack/easy-CSRF)[ Packagist](https://packagist.org/packages/itrack/csrf)[ Docs](https://github.com/itrack/easy-CSRF)[ RSS](/packages/itrack-csrf/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)DependenciesVersions (5)Used By (0)

Easy CSRF - Cross Site Request Forgery Protection
=================================================

[](#easy-csrf---cross-site-request-forgery-protection)

This library is a simple signature generator to protect form submissions from cross site request forgery, using a signed token. It does not require server-side storage of valid tokens and is thereby stateless.

Install
-------

[](#install)

composer require itrack/csrf

Simple usage
------------

[](#simple-usage)

```
$secret = '948thksehbf23fnoug2p4g2o...'; // well chosen secret
$signer = new \Itrack\CSRF\SignatureGenerator($secret);

if ($_POST) {
    if (!$signer->validateSignature($_POST['_token'])) {
        header('HTTP/1.0 400 Bad Request');
        exit;
    }
}
```

```

    getSignature()); ?>
    ...

```

The `SignatureGenerator` needs the be instantiated with the same secret every time. To generate a signed token, simply call `SignatureGenerator::getSignature` and embed the value into a hidden form field. Upon form submission, validate this token using `SignatureGenerator::validateSignature`.

Time limited validity
---------------------

[](#time-limited-validity)

The signature includes a timestamp of when it was generated. This can be used to expire it after some time. The timestamp is part of the signature generation process and cannot be altered. By default the signature expires after a few hours (see `SignatureGenerator::$validityWindow` for default value). You can set your own validity window using `SignatureGenerator::setValidityWindow`:

```
$signer->setValidityWindow(time() - 3600);
$signer->setValidityWindow('-1 hour');
$signer->setValidityWindow(new DateTime('-1 hour'));
```

The method accepts an integer UNIX timestamp, a string which will be evaluated by `strtotime` or an instance of `DateTime`. Any signature older than the set timestamp will be regarded as expired. The default timeout should present a reasonable value which makes sure signatures do expire eventually, without frustrating slow users. Adjust it to make it tighter or more relaxed based on your needs.

Adding data
-----------

[](#adding-data)

The signature can additionally be used to protect against form field injection and/or can be tied to a specific user. Data can be added to the signature generation process using `SignatureGenerator::addValue` and `SignatureGenerator::addKeyValue`:

```
$signer->addValue('foo');
$signer->addKeyValue('bar', 'baz');
```

The signature will only be valid if the same data was added when the token was generated and when it is being validated. To protect against form field injection you should add the names of all `` elements which you expect to receive in the submitted form using `SignatureGenerator::addValue`. Any additional data you want to tie to the signature, like the user id, should be added using `SignatureGenerator::addKeyValue`.

For example, when generating the token:

```
$signer = new \Itrack\CSRF\SignatureGenerator($secret);

// including user id in signature
// 'userid' is an arbitrarily chosen key name
$signer->addKeyValue('userid', $_SESSION['User']['id']);

// including names of valid form fields in signature
$signer->addValue('_token');
$signer->addValue('firstname');
$signer->addValue('lastname');
```

```

    getSignature()); ?>

```

When validating the token, use the submitted form fields as part of the validation:

```
$signer = new \Itrack\CSRF\SignatureGenerator($secret);

// including user id in signature validation
$signer->addKeyValue('userid', $_SESSION['User']['id']);

// including submitted form fields in signature validation
foreach (array_keys($_POST) as $key) {
    $signer->addValue($key);
}

if (!$signer->validateSignature($_POST['_token'])) {
    // error
}
```

This way, if any fields which were not part of the original signature are submitted with the form, it will not validate. Take care if you're dynamically adding form fields using Javascript.

### Note

[](#note)

The drawback of adding form fields is that the same form fields need to be added when generating the signature and when validating it. This requires to keep the list of expected and actual form fields in sync, which can quickly lead to code duplication if not handled properly. For best results I'd recommend using this library as part of a larger form generating function/class/library which handles this.

Signature format
----------------

[](#signature-format)

The signature is encoded in base64, format by default is:

```
timestamp + ":" + token + ":" + signed token

```

where

```
timestamp    = unsigned integer
token        = base64 encoded random value
signed token = base64 encoded hash

hash         = HMAC_SHA512(timestamp + token + data, secret)
data         = all added values

```

The `data` is sorted, so the order in which the values are added does not matter. The above description omits technical details on which exact format the data is put in for hashing, please consult the source code.

Crypto provider
---------------

[](#crypto-provider)

An alternative `CryptoProvider`, which provides a source of randomness and the hashing algorithm, can be passed upon instantiating `SignatureGenerator` as the second argument to the constructor. Consult `ICryptoProvider.php` and `CryptoProvider.php`.

Information
-----------

[](#information)

Based on  package

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity26

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 66.7% 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 ~835 days

Total

4

Last Release

2427d ago

Major Versions

0.1 → 1.02019-09-25

PHP version history (2 changes)0.1PHP &gt;=5.3.0

1.0PHP &gt;=7.0.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/59b3256e974f7816de4ef82f232f742e6f1e21517d72539a6f3792311c2eccc0?d=identicon)[itrack](/maintainers/itrack)

---

Top Contributors

[![deceze](https://avatars.githubusercontent.com/u/137217?v=4)](https://github.com/deceze "deceze (8 commits)")[![bradfora](https://avatars.githubusercontent.com/u/8585606?v=4)](https://github.com/bradfora "bradfora (2 commits)")[![aoberoi](https://avatars.githubusercontent.com/u/494795?v=4)](https://github.com/aoberoi "aoberoi (1 commits)")[![rickard2](https://avatars.githubusercontent.com/u/488425?v=4)](https://github.com/rickard2 "rickard2 (1 commits)")

---

Tags

csrfsecuritysecuritytokencsrfprotection

### Embed Badge

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

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

###  Alternatives

[phpmussel/phpmussel

PHP-based anti-virus anti-trojan anti-malware solution.

431228.1k1](/packages/phpmussel-phpmussel)[paragonie/anti-csrf

Paragon Initiative's Anti-CSRF Security Library

307200.6k5](/packages/paragonie-anti-csrf)[owasp/csrf-protector-php

CSRF protector php, a standalone php library for csrf mitigation in web applications. Easy to integrate in any php web app.

222348.3k4](/packages/owasp-csrf-protector-php)[kunststube/csrfp

A signed token generator for cross site request forgery protection.

52209.5k1](/packages/kunststube-csrfp)[riimu/kit-csrf

Secure and simple CSRF library protected against timing and BREACH attacks

6526.1k](/packages/riimu-kit-csrf)[ayesh/stateless-csrf

Secret-key based state-less CSRF token generator and validator for PHP 8. State-less means you do not have to store the CSRF token in session or database.

3223.3k](/packages/ayesh-stateless-csrf)

PHPackages © 2026

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