PHPackages                             bairwell/middleware-cors - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. bairwell/middleware-cors

ActiveLibrary[HTTP &amp; Networking](/categories/http)

bairwell/middleware-cors
========================

A PSR-7 middleware layer for providing CORS (Cross Origin Request Security) headers and security provisions. Instead of just allowing invalid CORs requests to come through, this middleware actively blocks them after validating.

v0.3.7(9y ago)1920.9k↓40.9%7[3 PRs](https://github.com/bairwell/middleware-cors/pulls)1MITPHPPHP ^7.0

Since Dec 30Pushed 3y ago1 watchersCompare

[ Source](https://github.com/bairwell/middleware-cors)[ Packagist](https://packagist.org/packages/bairwell/middleware-cors)[ Docs](https://github.com/bairwell/middleware-cors)[ RSS](/packages/bairwell-middleware-cors/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (5)Versions (10)Used By (1)

Bairwell\\Middleware-Cors
=========================

[](#bairwellmiddleware-cors)

[![Latest Stable Version](https://camo.githubusercontent.com/829c96a0747b3933651e0fcdcfc51293fc04a878b9b273ea14850b3770476e67/68747470733a2f2f706f7365722e707567782e6f72672f6261697277656c6c2f6d6964646c65776172652d636f72732f762f737461626c65)](https://packagist.org/packages/bairwell/middleware-cors)[![License](https://camo.githubusercontent.com/a3bc90c5146523ae4074397396f9f1c136aca7448928fe225323693a57b70c40/68747470733a2f2f706f7365722e707567782e6f72672f6261697277656c6c2f6d6964646c65776172652d636f72732f6c6963656e7365)](https://packagist.org/packages/bairwell/middleware-cors)[![SensioLabsInsight](https://camo.githubusercontent.com/67e93f3812e9f9a9ba7b1e2b9538ee8ffe0fb5e5f644eef08254d7e7b9920652/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f38616561393938372d653437382d346661612d613366652d3732386539343233623465372f6d696e692e706e67)](https://insight.sensiolabs.com/projects/8aea9987-e478-4faa-a3fe-728e9423b4e7)[![Coverage Status](https://camo.githubusercontent.com/67147b40578d440f0be40efb128280a54896d3ca23e2455fd905b7cd779565ed/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6261697277656c6c2f6d6964646c65776172652d636f72732f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://coveralls.io/github/bairwell/middleware-cors?branch=master)[![Build Status](https://camo.githubusercontent.com/8386920064675b9a8dc8f80e40d02877f908616d0e749b0fccb89b18429d27b3/68747470733a2f2f7472617669732d63692e6f72672f6261697277656c6c2f6d6964646c65776172652d636f72732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/bairwell/middleware-cors)[![Total Downloads](https://camo.githubusercontent.com/f33e0e1b270a14097e9fca83e3ca0fe43a9fa8ad08f6b77a27357cacebd40bec/68747470733a2f2f706f7365722e707567782e6f72672f6261697277656c6c2f6d6964646c65776172652d636f72732f646f776e6c6f616473)](https://packagist.org/packages/bairwell/middleware-cors)

This is a PHP 7 [Composer](https://getcomposer.org/) compatible library for providing a [PSR-7](http://www.php-fig.org/psr/psr-7/) compatible middleware layer for handling "[CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)" (Cross Origin Request Security/Cross-Origin Http Request/HTTP access control) headers and security.

What does this library provides over other CORs libraries?
----------------------------------------------------------

[](#what-does-this-library-provides-over-other-cors-libraries)

- PHP-7 type declarations.
- Works as a piece of [PSR-7](http://www.php-fig.org/psr/psr-7/) middleware making it compatible with many frameworks (such as [Slim 3](http://slimframework.com) and [Symfony](http://symfony.com/blog/psr-7-support-in-symfony-is-here))
- Massively flexibility over configuration settings (most can be strings, arrays or callbacks).
- Follows the [CORs flowchart](http://www.html5rocks.com/static/images/cors_server_flowchart.png) and actively rejects invalid requests.
- Only sends the appropriate headers when necessary.
- On CORs "OPTIONS" request, ensure a blank page 204 "No Content" page is returned instead of returning unwanted content bodies.
- Supports [PSR-3](http://www.php-fig.org/psr/psr-3/) based loggers for debugging purposes.
- Ignores non-CORs "OPTIONS" requests (for example, on REST services). A CORs request is indicated by the presence of the Origin: header on the inbound request.
- Fully unit tested.
- Licensed under the [MIT License](https://opensource.org/licenses/MIT) allowing you to practically do whatever you want.
- Uses namespaces and is 100% object orientated.
- Blocks invalid settings.
- Minimal third party requirements (just the definition files "[psr/http-message](https://github.com/php-fig/http-message)" and "[psr/log](https://github.com/php-fig/log)" as interface definitions, and [PHPUnit](https://phpunit.de/), [PHPCodeSniffer](http://www.squizlabs.com/php-codesniffer), and [Monolog](https://github.com/Seldaek/monolog) for development/testing).

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

[](#installation)

Install the latest version with Composer via:

```
$ composer require bairwell/middleware-cors
```

or by modifying your `composer.json` file:

```
{
  "require": {
    "bairwell/middleware-cors": "@stable"
  }
}

```

or from the Github repository (which is needed to be able to fork and contribute):

```
$ git clone git://github.com:bairwell/middleware-cors.git

```

Usage
=====

[](#usage)

You can utilise this CORs library as simply as:

```
$slim = new \Slim\App(); // use Slim3 as it supports PSR7 middleware

// add CORs
$slim->add(new MiddlewareCors());

// add routes
$slim->run(); // get Slim running
```

but that won't really add much (as it allows all hosts origin and methods by default).

You can make it slightly more complex by:

```
$slim = new \Slim\App(); // use Slim3 as it supports PSR7 middleware

$config = [
    'origin' => '*.example.com' // allow all hosts ending example.com
];

// add CORs
$slim->add(new MiddlewareCors($config));

// add routes
$slim->run(); // get Slim running
```

or

```
$slim = new \Slim\App(); // use Slim3 as it supports PSR7 middleware

$config = [
    'origin' => ['*.example.com', '*.example.com.test', 'example.com', 'dev.*'],
    'allowCredentials' => true
];

$slim->add(new MiddlewareCors($config)); // add CORs

// add routes
$slim->run(); // get Slim running
```

which will allow all Origins ending .example.com or \*.example.com.test, the exact example.com origin or any host starting with dev. It'll also allow credentials to be allowed.

For a more complicated integration which relies on the Slim router to feed back which methods are actually allowed per route, see `tests/MiddlewareCors/FunctionalTests/SlimTest.php`

Suggested settings
------------------

[](#suggested-settings)

```
// read the allowed methods for a route
$corsAllowedMethods = function (ServerRequestInterface $request) use ($container) : array {
    // if this closure is called, make sure it has the route available in the container.
    /* @var RouterInterface $router */
    $router = $container->get('router');

    $routeInfo = $router->dispatch($request);
    $methods = [];
    // was the method called allowed?
    if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
        $methods = $routeInfo[1];
    } else {
        // if it was, see if we can get the routes and then the methods from it.
        // @var \Slim\Route $route
        $route = $request->getAttribute('route');

        // has the request get a route defined? is so use that
        if (null !== $route) {
            $methods = $route->getMethods();
        }
    }

    // if we have methods, let's list them removing the OPTIONs one.
    if (0 === count($methods)) {
        // find the OPTIONs method
        $key = array_search('OPTIONS', $methods,true);
        // and remove it if set.
        if (false !== $key) {
            unset($methods[$key]);
            $methods = array_values($methods);
        }
    }

    return $methods;
};

$cors = new MiddlewareCors([
    'origin' => ['*.example.com','example.com','*.example.com.test','192.168.*','10.*'],
    'exposeHeaders' => '',
    'maxAge' => 120,
    'allowCredentials' => true,
    'allowMethods' => $corsAllowedMethods,
    'allowHeaders' => ['Accept', 'Accept-Language', 'Authorization', 'Content-Type','DNT','Keep-Alive','User-Agent','X-Requested-With','If-Modified-Since','Cache-Control','Origin'],
]);

$slim->add($cors);
```

Standards
---------

[](#standards)

The following [PHP FIG](http://www.php-fig.org/psr/) standards should be followed:

- [PSR 1 - Basic Coding Standard](http://www.php-fig.org/psr/psr-1/)
- [PSR 2 - Coding Style Guide](http://www.php-fig.org/psr/psr-2/)
- [PSR 3 - Logger Interface](http://www.php-fig.org/psr/psr-3/)
- [PSR 4 - Autoloading Standard](http://www.php-fig.org/psr/psr-4/)
- [PSR 5 - PHPDoc Standard](https://github.com/phpDocumentor/fig-standards/tree/master/proposed) - (still in draft)
- [PSR 7 - HTTP Message Interface](http://www.php-fig.org/psr/psr-7/)
- [PSR 12 - Extended Coding Style Guide](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md) - (still in draft)

### Standards Checking

[](#standards-checking)

[PHP Code Sniffer](https://github.com/squizlabs/PHP_CodeSniffer/) highlights potential coding standards issues.

`vendor/bin/phpcs`

PHP CS will use the configuration in `phpcs.xml.dist` by default.

To see which sniffs are running add "-s"

Unit Tests
----------

[](#unit-tests)

[PHPUnit](http://phpunit.de) is installed for unit testing (tests are in `tests`)

To run unit tests: `vendor/bin/phpunit`

For a list of the tests that have ran: `vendor/bin/phpunit --tap`

To restrict the tests run: `vendor/bin/phpunit --filter 'MiddlewareCors\\Exceptions\\BadOrigin'`

or just

`vendor/bin/phpunit --filter 'ExceptionTest'`

for all tests which have "Exception" in them and: `vendor/bin/phpunit --filter '(ExceptionTest::testEverything|ExceptionTest::testStub)'`

to test the two testEverything and testStub methods in the ExceptionTest class (for example).

Licence/License
===============

[](#licencelicense)

Licenced under the MIT license. See LICENSE.md for full information.

Bairwell/MiddlewareCors is Copyright (c) Bairwell Ltd/Richard Bairwell 2016.

Supporting development
======================

[](#supporting-development)

You can help support development of this library via a variety of methods:

- "Sponsorship" via a monthly donation via [Patreon](https://www.patreon.com/rbairwell)
- [Reporting issues](https://github.com/bairwell/middleware-cors/issues)
- Making updates via [Github](https://github.com/bairwell/middleware-cors)
- Spreading the word.
- Just letting me know what you think of it via [Twitter](http://twitter.com/rbairwell) or via [Bairwell Ltd](http://www.bairwell.com)

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.6% 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 ~25 days

Recently: every ~37 days

Total

7

Last Release

3637d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/16501974?v=4)[Bairwell Ltd](/maintainers/bairwell)[@bairwell](https://github.com/bairwell)

---

Top Contributors

[![rbairwell](https://avatars.githubusercontent.com/u/775269?v=4)](https://github.com/rbairwell "rbairwell (25 commits)")[![B3none](https://avatars.githubusercontent.com/u/24966460?v=4)](https://github.com/B3none "B3none (1 commits)")[![xnan-dev](https://avatars.githubusercontent.com/u/105134243?v=4)](https://github.com/xnan-dev "xnan-dev (1 commits)")

---

Tags

phppsr7psr7-middlewarepsr-7middlewarecorscross origin request security

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/bairwell-middleware-cors/health.svg)

```
[![Health](https://phpackages.com/badges/bairwell-middleware-cors/health.svg)](https://phpackages.com/packages/bairwell-middleware-cors)
```

###  Alternatives

[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

1331.8M24](/packages/tuupola-cors-middleware)[neomerx/cors-psr7

Framework agnostic (PSR-7) CORS implementation (www.w3.org/TR/cors/)

682.4M19](/packages/neomerx-cors-psr7)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28483.0k2](/packages/mezzio-mezzio-authentication-oauth2)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)[jimtools/jwt-auth

PSR-15 JWT Authentication middleware, A replacement for tuupola/slim-jwt-auth

20142.3k3](/packages/jimtools-jwt-auth)

PHPackages © 2026

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