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

ActiveLibrary[Security](/categories/security)

adbario/slim-csrf
=================

CSRF protection for Slim 3 framework

1.1.0(9y ago)42.8k2MITPHPPHP &gt;=5.5

Since Sep 13Pushed 9y ago3 watchersCompare

[ Source](https://github.com/adbario/slim-csrf)[ Packagist](https://packagist.org/packages/adbario/slim-csrf)[ Docs](https://github.com/adbario/slim-csrf)[ RSS](/packages/adbario-slim-csrf/feed)WikiDiscussions master Synced 4w ago

READMEChangelog (3)Dependencies (2)Versions (4)Used By (0)

Slim CSRF Protection
====================

[](#slim-csrf-protection)

Protection against CSRF in [Slim 3 framework](http://www.slimframework.com/). Uses [Slim Secure Session Middleware](https://github.com/adbario/slim-secure-session-middleware) to manage session and automatically creates HTML form hidden input for [Twig-View](https://github.com/slimphp/Twig-View) and [PHP-View](https://github.com/slimphp/PHP-View).

CSRF protection will be applied to POST, PUT, DELETE and PATCH requests.

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

[](#installation)

```
composer require adbario/slim-csrf

```

Usage
-----

[](#usage)

### Depency Container

[](#depency-container)

Inject session helper to application container ([read more about session helper](https://github.com/adbario/slim-secure-session-middleware)):

```
$container['session'] = function ($container) {
    return new \Adbar\Session(
        $container->get('settings')['session']['namespace']
    );
};
```

Inject CSRF protection in application container:

```
$container['csrf'] = function ($c) {
    return new \Adbar\Slim\Csrf($c->get('session'));
};
```

If you use Twig-View or PHP-View:

```
$container['csrf'] = function ($c) {
    return new \Adbar\Slim\Csrf(
        $c->get('session'),
        $c->get('view')
    );
};
```

### Other dependencies

[](#other-dependencies)

CSRF protection needs Slim Secure Session Middleware. [Inject settings](https://github.com/adbario/slim-secure-session-middleware) for session middleware and register it:

```
$app->add(new \Adbar\SessionMiddleware($container->get('settings')['session']));
```

### Register for all routes

[](#register-for-all-routes)

To use CSRF protection on all routes, register it as a middleware before session middleware:

```
/** Csrf */
$app->add($app->getContainer()->get('csrf'));

/** Session */
$app->add(new \Adbar\SessionMiddleware($container->get('settings')['session']));
```

### Register per route

[](#register-per-route)

To use CSRF protection on specific routes, add it like this:

```
$app->get('/form', function ($request, $response) {
    // CSRF token will be added
    return $this->view->render($response, 'form.twig');
})->add($container->get('csrf'));

$app->post('/form', function ($request, $response) {
    // If CSRF token was valid, code after this will run
})->add($container->get('csrf'));
```

### Twig-View

[](#twig-view)

Ready-to-use HTML form hidden input will be injected in Twig-View, to use it in your view:

```

    {{ csrf|raw }}
    Username

```

### PHP-View

[](#php-view)

Ready-to-use HTML form hidden input will be injected also in Twig-View, to use it in your view:

```

    Username

```

### Other template engines

[](#other-template-engines)

You can easily use CSRF protection on other template engines as well. Inject to container without view:

```
$container['csrf'] = function () {
    return new \Adbar\Slim\Csrf;
};
```

Generate HTML hidden input field:

```
$app->get('/form', function ($request, $response) {
    // Generate form field
    $csrf = $this->csrf->generateForm();
    // Inject form field to your view...
});
```

### Custom error on CSRF token failure

[](#custom-error-on-csrf-token-failure)

By default, CSRF protection shows simple message on failure:

```
Invalid security token.

```

You can render a custom template if CSRF token isn't valid, edit container:

```
$container['csrf'] = function ($c) {
    $csrf = new \Adbar\Slim\Csrf(
        $c->get('session'),
        $c->get('view')
    );
    $csrf->setTokenError(function ($request, $response, $next) use ($c) {
        return $c->view->render($response->withStatus(400), 'csrf_error.twig');
    });
    return $csrf;
};
```

If you just want to edit simple message:

```
$container['csrf'] = function ($c) {
    $csrf = new \Adbar\Slim\Csrf(
        $c->get('session'),
        $c->get('view')
    );
    $csrf->setTokenErrorMessage('This is my custom error message.');
    return $csrf;
};
```

License
-------

[](#license)

[MIT license](LICENSE.md)

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity60

Established project with proven stability

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

Total

3

Last Release

3372d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/22136575?v=4)[Riku Sarkinen](/maintainers/adbario)[@adbario](https://github.com/adbario)

---

Top Contributors

[![adbario](https://avatars.githubusercontent.com/u/22136575?v=4)](https://github.com/adbario "adbario (14 commits)")

---

Tags

slimtokencsrf

### Embed Badge

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

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

###  Alternatives

[aura/session

Provides session management functionality, including lazy session starting, session segments, next-request-only ("flash") values, and CSRF tools.

2051.2M76](/packages/aura-session)[kunststube/csrfp

A signed token generator for cross site request forgery protection.

47210.7k1](/packages/kunststube-csrfp)[paragonie/anti-csrf

Paragon Initiative's Anti-CSRF Security Library

304211.3k5](/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.

215363.8k5](/packages/owasp-csrf-protector-php)[kelvinmo/fernet-php

An implementation of the Fernet token specification in PHP.

211.8M3](/packages/kelvinmo-fernet-php)[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.

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

PHPackages © 2026

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