PHPackages                             alexsoft/cross-origin-protection - 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. alexsoft/cross-origin-protection

ActiveLibrary[Security](/categories/security)

alexsoft/cross-origin-protection
================================

Cross Origin Protection middleware that uses Sec-Fetch-Site and Origin headers

1.0.0(5mo ago)03[4 issues](https://github.com/alexsoft/cross-origin-protection/issues)MITPHPPHP ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0CI passing

Since Nov 9Pushed 2mo agoCompare

[ Source](https://github.com/alexsoft/cross-origin-protection)[ Packagist](https://packagist.org/packages/alexsoft/cross-origin-protection)[ RSS](/packages/alexsoft-cross-origin-protection/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)DependenciesVersions (6)Used By (0)

Cross Origin Protection [![Latest Version on Packagist](https://camo.githubusercontent.com/b8b12a453a6a3c5e229a632089b68f1390d01da0a6fe1cd884b074d50dd77785/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c6578736f66742f63726f73732d6f726967696e2d70726f74656374696f6e2e7376673f7374796c653d666c6174)](https://packagist.org/packages/alexsoft/cross-origin-protection) [![codecov](https://camo.githubusercontent.com/0bb0c1cc06fcd75a97b6dca706cc46cd1449f97045cc0b88c0cd5646c5bcfd98/68747470733a2f2f636f6465636f762e696f2f6769746875622f616c6578736f66742f63726f73732d6f726967696e2d70726f74656374696f6e2f67726170682f62616467652e7376673f746f6b656e3d47444c4a38354e453151)](https://codecov.io/github/alexsoft/cross-origin-protection)
========================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#cross-origin-protection--)

This library is a port of [CrossOriginProtection component](https://pkg.go.dev/net/http#CrossOriginProtection) from Go.

You can read an introduction to the mentioned Go component here: [alexedwards.net/blog/preventing-csrf-in-go](https://www.alexedwards.net/blog/preventing-csrf-in-go).

Overview
--------

[](#overview)

This is a small PSR-15/PSR-7-compatible middleware library for PHP which validates fetch metadata (Sec-Fetch-Site) and Origin headers. It follows the approach popularised by the Go CrossOriginProtection component.

This middleware is focused on rejecting unsafe cross-origin requests (a practical defense against certain CSRF/forged-request scenarios).

### Why use this

[](#why-use-this)

Protect state-changing endpoints from cross-site requests when browser fetch metadata is available.

Lightweight, framework-agnostic middleware for PSR-compatible stacks.

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

[](#installation)

Install with Composer:

```
composer require alexsoft/cross-origin-protection:^1.0
```

Usage
-----

[](#usage)

```
use Alexsoft\CrossOriginProtection\CrossOriginProtection;
use GuzzleHttp\Psr7\Request;

$result = (new CrossOriginProtection())->check(Request::fromGlobals()); // accepts instance of ServerRequestInterface

if ($result === null) {
    // request is considered safe
} else {
    // request is NOT considered safe
}
```

If `$result` is not `null`, it will be an instance of `CrossOriginRequestError` which has public property `$message` which can be used for logging. Usually it is discouraged to show this message to the user, it is preferable to show some more generic server error message.

PSR-15 middleware usage
-----------------------

[](#psr-15-middleware-usage)

Get instance of `Psr\Http\Server\MiddlewareInterface` by calling `getMiddleware()` method. Then you can plug it into your stack.

```
use Alexsoft\CrossOriginProtection\CrossOriginProtection;

$psr15Middleware = (new CrossOriginProtection())->getMiddleware();
```

Configuration
-------------

[](#configuration)

`CrossOriginProtection` has 2 method that provide extension:

- `addInsecureBypassPattern(string $regex): void` – can be used to add **case-insensitive** regex for the URLs that need to be bypassed. All added regexes are combined with `|`, wrapped with leading and trailing slashes and have `i` (ignore case) flag added.
- `addTrustedOrigin(string|UriInterface $uri): void` – can be used to add trusted origins for which requests should be bypassed.

```
use Alexsoft\CrossOriginProtection\CrossOriginProtection;
use GuzzleHttp\Psr7\Request;

$crossOriginProtection = new CrossOriginProtection();

$crossOriginProtection->addInsecureBypassPattern('\/internal\/'); // will bypass URLS with '/internal/' section in it

$crossOriginProtection->addTrustedOrigin('https://example.com');

// can be used directly
$crossOriginProtection->check(Request::fromGlobals()); // accepts instance of ServerRequestInterface

// or as PSR-15 middleware
$middleware = $crossOriginProtection->getMiddleware();
```

Important notes
---------------

[](#important-notes)

Because the middleware relies on browser-provided `Sec-Fetch-Site` and `Origin` headers, consider following:

### Safe methods

[](#safe-methods)

You typically only need to apply strict checks to state-changing methods (e.g. `POST`, `PUT`, `DELETE`, `PATCH`). `GET`, `HEAD` are usually safe but evaluate per-API.

### Fetch metadata support

[](#fetch-metadata-support)

`Sec-Fetch-Site` is not present in all browsers/clients. Falling back on comparing Origin and Host when `Sec-Fetch-Site` is missing can be risky: `Host` lacks scheme and that fallback has edge cases (e.g.  vs ). This should be mitigated with HTTP Strict Transport Security (HSTS). See the article for nuances.

### Not a complete protection

[](#not-a-complete-protection)

This middleware helps reject unsafe cross-origin requests but is not a complete CSRF protection on its own. Use it alongside other controls (CSRF tokens for browser forms, SameSite cookies, strong authentication).

When `Sec-Fetch-Site` is absent, implementation falls back to `Origin` vs `Host` checks; this fallback may introduce false-positives/negatives in mixed-scheme deployments (HTTP ↔ HTTPS). Test carefully.

Do not depend on header values from non-browser clients — spoilable by attackers. The middleware is primarily to harden browser-based attack surfaces.

###  Health Score

40

—

FairBetter than 87% of packages

Maintenance85

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

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

Total

3

Last Release

166d ago

PHP version history (2 changes)1.0.0-rc1PHP ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0

1.0.0PHP ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/8b007906f72b36ec7614b7a0a5d4455e5e40c2fdfc3c7e4b9b3d605c379664b7?d=identicon)[alexsoft](/maintainers/alexsoft)

---

Top Contributors

[![alexsoft](https://avatars.githubusercontent.com/u/1451894?v=4)](https://github.com/alexsoft "alexsoft (44 commits)")

---

Tags

middlewarecross-originprotection

### Embed Badge

![Health badge](/badges/alexsoft-cross-origin-protection/health.svg)

```
[![Health](https://phpackages.com/badges/alexsoft-cross-origin-protection/health.svg)](https://phpackages.com/packages/alexsoft-cross-origin-protection)
```

###  Alternatives

[phpmussel/phpmussel

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

431228.1k1](/packages/phpmussel-phpmussel)[masterro/laravel-xss-filter

Filter user input for XSS but don't touch other html

41254.5k](/packages/masterro-laravel-xss-filter)[stevenmaguire/laravel-middleware-csp

Provides support for enforcing Content Security Policy with headers in Laravel responses.

39107.6k](/packages/stevenmaguire-laravel-middleware-csp)[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)[causal/fal-protect

Protect everything within /fileadmin/ based on associated folder and file restrictions (visibility, user groups and dates of publication).

1269.5k](/packages/causal-fal-protect)[bnomei/kirby3-redirects

Setup performant HTTP Status Code Redirects from within the Kirby Panel

269.1k](/packages/bnomei-kirby3-redirects)

PHPackages © 2026

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