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

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

christoph-kluge/reactphp-http-cors-middleware
=============================================

A cors middleware for the ReactPHP HTTP-Server

2.0.0(5y ago)1010.6k↑150%5[1 issues](https://github.com/christoph-kluge/reactphp-http-cors-middleware/issues)3MITPHPPHP &gt;=5.6.0CI failing

Since Apr 4Pushed 4y ago3 watchersCompare

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

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

ReactPHP Cors Middleware
========================

[](#reactphp-cors-middleware)

This middleware implements [Cross-origin resource sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) for ReactPHP. This repository got mainly inspired by [tuupola/cors-middleware](https://github.com/tuupola/cors-middleware). Additional configuration ideas got taken from [barryvdh/laravel-cors](https://github.com/barryvdh/laravel-cors) and [nelmio/NelmioCorsBundle](https://github.com/nelmio/NelmioCorsBundle). The internal heavy lifting is done by [neomerx/cors-psr7](https://github.com/neomerx/cors-psr7) library.

[![Build Status](https://camo.githubusercontent.com/547fade03a365ce006dc04f911fad6db271dfa34fc77848434b808e295a65f07/68747470733a2f2f7472617669732d63692e6f72672f6368726973746f70682d6b6c7567652f72656163747068702d687474702d636f72732d6d6964646c65776172652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/christoph-kluge/reactphp-http-cors-middleware)[![Total Downloads](https://camo.githubusercontent.com/99ffe29bf4e83b6f08fa25d1ac17104c3cac9c7e02a253379129b022039e4b84/68747470733a2f2f706f7365722e707567782e6f72672f6368726973746f70682d6b6c7567652f72656163747068702d687474702d636f72732d6d6964646c65776172652f646f776e6c6f616473)](https://packagist.org/packages/christoph-kluge/reactphp-http-cors-middleware)[![License](https://camo.githubusercontent.com/4928c8f48c4d2e81743088e763e43d2de1b424461f435a022aa1294f95d0a568/68747470733a2f2f706f7365722e707567782e6f72672f6368726973746f70682d6b6c7567652f72656163747068702d687474702d636f72732d6d6964646c65776172652f6c6963656e7365)](https://packagist.org/packages/christoph-kluge/reactphp-http-cors-middleware)

Install
=======

[](#install)

To install via [Composer](http://getcomposer.org/), use the command below, it will automatically detect the latest version and bind it with `^`.

```
composer require christoph-kluge/reactphp-http-cors-middleware

```

This middleware will detect CORS requests and will intercept the request if there is something invalid.

Usage
=====

[](#usage)

```
$server = new HttpServer(
    new CorsMiddleware(),
    function (ServerRequestInterface $request, callable $next) {
        return new Response(200, ['Content-Type' => 'text/html'], 'We test CORS');
    },
);
```

Configuration
=============

[](#configuration)

The defaults for this middleware are mainly taken from [enable-cors.org](https://enable-cors.org).

Available configuration options
-------------------------------

[](#available-configuration-options)

Thanks to [expressjs/cors#configuring-cors](https://github.com/expressjs/cors#configuring-cors). As I took most configuration descriptions from there.

- `server_url`: can be used to set enable strict `Host` header checks to avoid malicious use of our server. (default: `null`)
- `response_code`: can be used to set the HTTP-StatusCode on a successful `OPTIONS` / Pre-Flight-Request (default: `204`)
- `allow_credentials`: Configures the `Access-Control-Allow-Credentials` CORS header. Expects an boolean (ex: `true` // to set the header)
- `allow_origin`: Configures the `Access-Control-Allow-Origin` CORS header. Expects an array (ex: `['http://example.net', 'https://example.net']`).
- `allow_origin_callback`: Will set `allow_origin` to an empty array `[]` and use the callback on a per-request base. The first parameter is an instance of `ParsedUrlInterface` and the callback is expected to return an `boolean`.
- `allow_methods`: Configures the `Access-Control-Allow-Methods` CORS header. Expects an array (ex: `['GET', 'PUT', 'POST']`).
- `allow_headers`: Configures the `Access-Control-Allow-Headers` CORS header. Expects an array (ex: `['Content-Type', 'Authorization']`).
- `expose_headers`: Configures the `Access-Control-Expose-Headers` CORS header. Expects an array (ex: `['Content-Range', 'X-Content-Range']`).
- `max_age`: Configures the `Access-Control-Max-Age` CORS header. Expects an integer representing seconds (ex: `1728000` // 20 days)

Default Settings (Allow All CORS Requests)
------------------------------------------

[](#default-settings-allow-all-cors-requests)

```
$settings = [
    'allow_credentials' => true,
    'allow_origin'      => ['*'],
    'allow_methods'     => ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'],
    'allow_headers'     => ['DNT','X-Custom-Header','Keep-Alive','User-Agent','X-Requested-With','If-Modified-Since','Cache-Control','Content-Type','Content-Range','Range'],
    'expose_headers'    => ['DNT','X-Custom-Header','Keep-Alive','User-Agent','X-Requested-With','If-Modified-Since','Cache-Control','Content-Type','Content-Range','Range'],
    'max_age'           => 60 * 60 * 24 * 20, // preflight request is valid for 20 days
];
```

Allow specific origins (Origin requires scheme, host and optionally port)
-------------------------------------------------------------------------

[](#allow-specific-origins-origin-requires-scheme-host-and-optionally-port)

```
$server = new HttpServer(
    new CorsMiddleware([
        'allow_origin' => [
            'http://www.example.net',
            'https://www.example.net',
            'http://www.example.net:8443',
        ],
    ])
);
```

Allow origins on a per-request base (callback)
----------------------------------------------

[](#allow-origins-on-a-per-request-base-callback)

```
$server = new HttpServer(
    new CorsMiddleware([
        'allow_origin'          => [],
        'allow_origin_callback' => function(ParsedUrlInterface $origin) {
            // do some evaluation magic with origin ..
            return true;
        },
    ])
);
```

Use custom response code on pre-flight requests
-----------------------------------------------

[](#use-custom-response-code-on-pre-flight-requests)

Some legacy browsers choke on 204. Thanks to [expressjs/cors#configuring-cors](https://github.com/expressjs/cors#configuring-cors) for that.

```
$server = new HttpServer(
    new CorsMiddleware([
        'response_code' => 200,
    ])
);
```

Use strict host checking
------------------------

[](#use-strict-host-checking)

The default handling of this middleware will allow any "Host"-header. This means that you can use your server with any hostname you want. This might be a desired behavior but allows also the misuse of your server.

To prevent such a behavior there is a `server_url` option which will enable strict host checking. In this scenario the server will return a `403` with the body `Origin not allowed`.

```
$server = new HttpServer(
    new CorsMiddleware([
        'server_url' => 'http://api.example.net:8080'
    ])
);
```

License
=======

[](#license)

The MIT License (MIT)

Copyright (c) 2017 Christoph Kluge

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity31

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 79.3% 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 ~450 days

Total

3

Last Release

2057d ago

Major Versions

1.0.1 → 2.0.02020-09-19

### Community

Maintainers

![](https://www.gravatar.com/avatar/23a3cbb346a78c868a78c52864ac0f3fe70a6cbabc488cefcf121e1d16006737?d=identicon)[christoph-kluge](/maintainers/christoph-kluge)

---

Top Contributors

[![christoph-kluge](https://avatars.githubusercontent.com/u/1446269?v=4)](https://github.com/christoph-kluge "christoph-kluge (23 commits)")[![WyriHaximus](https://avatars.githubusercontent.com/u/147145?v=4)](https://github.com/WyriHaximus "WyriHaximus (4 commits)")[![Alban-io](https://avatars.githubusercontent.com/u/7300483?v=4)](https://github.com/Alban-io "Alban-io (1 commits)")[![sandrokeil](https://avatars.githubusercontent.com/u/3597436?v=4)](https://github.com/sandrokeil "sandrokeil (1 commits)")

---

Tags

corsmiddlewarereactphp

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/christoph-kluge-reactphp-http-cors-middleware/health.svg)

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

###  Alternatives

[league/uri-interfaces

Common tools for parsing and resolving RFC3987/RFC3986 URI

538204.9M23](/packages/league-uri-interfaces)[shopify/shopify-api

Shopify API Library for PHP

4634.8M16](/packages/shopify-shopify-api)[laudis/neo4j-php-client

Neo4j-PHP-Client is the most advanced PHP Client for Neo4j

184616.9k31](/packages/laudis-neo4j-php-client)[discord-php/http

Handles HTTP requests to Discord servers

25318.7k8](/packages/discord-php-http)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[clue/soap-react

Simple, async SOAP webservice client library, built on top of ReactPHP

64118.0k1](/packages/clue-soap-react)

PHPackages © 2026

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