PHPackages                             thecodingmachine/csrf-header-check-middleware - 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. thecodingmachine/csrf-header-check-middleware

ActiveLibrary

thecodingmachine/csrf-header-check-middleware
=============================================

A PHP PSR-15 compliant middleware that checks for CSRF attacks.

v2.0.0(8y ago)730.0k↓100%31MITPHPPHP &gt;=7

Since Jun 12Pushed 7y ago6 watchersCompare

[ Source](https://github.com/thecodingmachine/csrf-header-check-middleware)[ Packagist](https://packagist.org/packages/thecodingmachine/csrf-header-check-middleware)[ RSS](/packages/thecodingmachine-csrf-header-check-middleware/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (4)Used By (1)

[![Latest Stable Version](https://camo.githubusercontent.com/3e836a773982383807f7aed72ed057962bfc274f9fa764c0e8e9d59c943371b1/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f637372662d6865616465722d636865636b2d6d6964646c65776172652f762f737461626c65)](https://packagist.org/packages/thecodingmachine/csrf-header-check-middleware)[![Total Downloads](https://camo.githubusercontent.com/3436258b345103c5df1b6358698ae1b5adb7a06f3008d12860c4ad93c9a3397b/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f637372662d6865616465722d636865636b2d6d6964646c65776172652f646f776e6c6f616473)](https://packagist.org/packages/thecodingmachine/csrf-header-check-middleware)[![Latest Unstable Version](https://camo.githubusercontent.com/78e46521747ec09dc9484995a69f0771b0d0e84e96f2664d9fe449e60b8dd064/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f637372662d6865616465722d636865636b2d6d6964646c65776172652f762f756e737461626c65)](https://packagist.org/packages/thecodingmachine/csrf-header-check-middleware)[![License](https://camo.githubusercontent.com/d907326b51fa457b0348a1f1606593e5a51e32c8457249d216241a684959776a/68747470733a2f2f706f7365722e707567782e6f72672f746865636f64696e676d616368696e652f637372662d6865616465722d636865636b2d6d6964646c65776172652f6c6963656e7365)](https://packagist.org/packages/thecodingmachine/csrf-header-check-middleware)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/2b31751ac1a6d4b1c384de98337ad96ecfeb25201588755b1037ca116a52dbeb/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f746865636f64696e676d616368696e652f637372662d6865616465722d636865636b2d6d6964646c65776172652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/thecodingmachine/csrf-header-check-middleware/?branch=master)[![Build Status](https://camo.githubusercontent.com/fb8f74fed54f29c75af1a4707120e0161be1f93ddbc95c32ec01bc2dfc3e6d3e/68747470733a2f2f7472617669732d63692e6f72672f746865636f64696e676d616368696e652f637372662d6865616465722d636865636b2d6d6964646c65776172652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/thecodingmachine/csrf-header-check-middleware)[![Coverage Status](https://camo.githubusercontent.com/3f0ecbcb03ca754d2b73d75b2ef0e3aceeb3c89e8b234d8563c238fb14705faa/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f746865636f64696e676d616368696e652f637372662d6865616465722d636865636b2d6d6964646c65776172652f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://coveralls.io/github/thecodingmachine/csrf-header-check-middleware?branch=master)

CSRF header checking middleware
===============================

[](#csrf-header-checking-middleware)

This package contains a PHP PSR-15 compliant middleware that checks for CSRF attacks.

It implements the [first OWASP general recommendation for guarding your site against cross-site request forgery (Verifying Same Origin with Standard Headers)](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet).

Note that OWASP recommends also using a CSRF token. This requires some changes in your application and this middleware does not provide any help regarding CSRF token generation. Other packages (like [Slim-CSRF](https://github.com/slimphp/Slim-Csrf)) can help you with CSRF token validation.

What is it doing?
-----------------

[](#what-is-it-doing)

The `CsrfHeaderCheckMiddleware` will look at all POST/PUT/DELETE requests (actually all requests that are not GET/HEAD/OPTIONS). It will verify that the "Origin" of the request is your own website.

It does so by comparing the "Origin" (or the "Referrer" header as a fallback) to your website's domain name. If the headers do not match (or if the headers are not found), it will trigger an exception.

Why does it work?
-----------------

[](#why-does-it-work)

In a CSRF attack, the victim (Alice) is logged in your application. The attacker (Eve) sends Alice a malicious link to her malicious website. The malicious website contains some Javascript that performs a POST on a form of your website. Since Alice is logged into your website, the POST succeeds, allowing Eve to perform actions on the behalf of Alice.

The query is therefore executed by Alice's computer. We can expect Alice's browser to behave as a "normal" browsers.

Normal browsers [do not allow Javascript code to modify the "Origin" or "Referer" header](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name).

How does it compare to other solutions
--------------------------------------

[](#how-does-it-compare-to-other-solutions)

When fighting CSRF attacks, the most common solution used it to generate a token in each form, store this token in session, and check that the user sends back the token. If you are looking for a CSRF token based middleware using PSR-7/PSR-15, have a look at [Ocramius/PSR7Csrf](https://github.com/Ocramius/PSR7Csrf/)

### Advantages over token based implementations

[](#advantages-over-token-based-implementations)

Checking for HTTP headers can be done in the middleware alone. With token-based middlewares, you have to modify your application to generate a token and send the token with any form. In contrast, checking headers requires no work besides adding the middleware. So it's really fast to deploy.

### Limits

[](#limits)

- This middleware completely bypasses GET requests. If your application modifies state on GET requests, you are screwed. Of course, modification of state should only happen in POST requests (but please check twice that your routes changing state do ONLY works with POST/DELETE/PUT requests).
- This middleware expects "Origin" or "Referer" headers to be filled. This will often be true unless you are in a corporate environment with proxies that are fiddling with your request. For instance, some proxies are known to strip headers in order to make the request anonymous.
- Will block CORS requests. You cannot use this middleware if you are expecting requests to come from another origin than your website.
- If your website is accessed from a third party application (like a phone app), you cannot use this middleware as the Origin and Referer will be empty.

If you are in one of those situations, use a token-based middleware instead.

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

[](#installation)

```
composer require thecodingmachine/csrf-header-check-middleware
```

Usage
-----

[](#usage)

The simplest usage is based on defaults. It assumes that you have a configured PSR-7 compatible application that supports piping middlewares.

In a [`zendframework/zend-expressive`](https://github.com/zendframework/zend-expressive)application, the setup would look like the following:

```
$app = \Zend\Expressive\AppFactory::create();

$app->pipe(\TheCodingMachine\Middlewares\CsrfHeaderCheckMiddlewareFactory::createDefault();
```

Guessing your domain name
-------------------------

[](#guessing-your-domain-name)

This middleware will do its best to "guess" the domain name of your website. To do so, it will check the "Host" header of the HTTP request.

You need to know this:

- Normal browsers always send the "Host" header (at least in HTTP 1.1).
- In a normal browser, the "Host" header cannot be modified by Javascript code.

However:

- The "Host" header can be modified by proxies
- Proxies will generally put the previous "Host" header in the "X-Forwarded-Host" header
- The "X-Forwarded-Host" header CANNOT be trusted because it can be changed from the client side (in Javascript)

Therefore, if you run your application behind a proxy, or if you deal for some reason with HTTP/1.0, you will have to manually specify the domain name of your application.

```
// The first argument of the factory is a list of domain name for your application.
$app->pipe(\TheCodingMachine\Middlewares\CsrfHeaderCheckMiddlewareFactory::createDefault([
    'alice.com',
    'www.alice.com'
]);
```

Disabling CSRF checks
---------------------

[](#disabling-csrf-checks)

You can disable CSRF checks on a per-route basis:

```
// The second argument of the factory is a list of regular expressions that will be matched on the path.
// Here, we disable CSRF checks on /api/*
$app->pipe(\TheCodingMachine\Middlewares\CsrfHeaderCheckMiddlewareFactory::createDefault([], [
    '#^/api/#'
]);
```

This can be useful for APIs that are only used when communicating from server to server. Please note that if you decide to disable CSRF for some routes, you need to have some other forms of protection for this route.

Alternatively, any request passed to the middleware that has the 'TheCodingMachine\\BypassCsrf' attribute set will be ignored:

```
// Put this in a middleware placed before the `CsrfHeaderCheckMiddleware` to disable it.
$request = $request->withAttribute('TheCodingMachine\\BypassCsrf', true);
```

###  Health Score

36

—

LowBetter than 81% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity31

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity65

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

Total

3

Last Release

2992d ago

Major Versions

v1.0.0-beta1 → v2.0.02018-02-27

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1104771?v=4)[mouf](/maintainers/mouf)[@Mouf](https://github.com/Mouf)

![](https://avatars.githubusercontent.com/u/1847918?v=4)[TheCodingMachine](/maintainers/thecodingmachine)[@thecodingmachine](https://github.com/thecodingmachine)

---

Top Contributors

[![moufmouf](https://avatars.githubusercontent.com/u/1290952?v=4)](https://github.com/moufmouf "moufmouf (13 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/thecodingmachine-csrf-header-check-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/thecodingmachine-csrf-header-check-middleware/health.svg)](https://phpackages.com/packages/thecodingmachine-csrf-header-check-middleware)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5723.1M30](/packages/thecodingmachine-graphqlite)[cakephp/authentication

Authentication plugin for CakePHP

1153.6M67](/packages/cakephp-authentication)[neos/flow

Flow Application Framework

862.0M449](/packages/neos-flow)[cakephp/authorization

Authorization abstraction layer plugin for CakePHP

742.2M34](/packages/cakephp-authorization)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)

PHPackages © 2026

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