PHPackages                             txc/cors-psr7 - 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. txc/cors-psr7

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

txc/cors-psr7
=============

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

v1.0.0(2y ago)05Apache-2.0PHPPHP ^7.2 || ^8.0

Since Sep 13Pushed 2y agoCompare

[ Source](https://github.com/TXC/cors-psr7)[ Packagist](https://packagist.org/packages/txc/cors-psr7)[ Docs](https://github.com/TXC/cors-psr7)[ RSS](/packages/txc-cors-psr7/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (3)Used By (0)

[![codecov](https://camo.githubusercontent.com/af947ec1bf6538aeb6ddf90bce316289dabe94b2d1c0654163d5bab4c7276676/68747470733a2f2f636f6465636f762e696f2f67682f5458432f636f72732d707372372f67726170682f62616467652e7376673f746f6b656e3d377a554a326f5a663338)](https://codecov.io/gh/TXC/cors-psr7)[![License](https://camo.githubusercontent.com/f39bcdf0321b2d052862d39f7371de407052f14c97fec0ed96dfb3b2d94a2224/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f5458432f636f72732d707372372e737667)](https://packagist.org/packages/txc/cors-psr7)

Why This Fork?
--------------

[](#why-this-fork)

Since [neomerx/cors-psr7](https://github.com/neomerx/cors-psr7) doesn't support PHP 8.1+ i forked and updated it to do so.

This package is replacing [neomerx/cors-psr7](https://github.com/neomerx/cors-psr7), so usage with for example [middlewares/cors](https://github.com/middlewares/cors/) should only require you to include this package.

```
{
  "require": {
    ...
    "txc/cors-psr7": "^1.0",
    "middlewares/cors": "^2.0",
    ...
  },
}
```

[![Code Coverage](https://camo.githubusercontent.com/f00bc43b27db5a6e6341d3374060a401be1ed2cdbba1a881394a70c0f211f260/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e656f6d6572782f636f72732d707372372f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/neomerx/cors-psr7/?branch=master)[![License](https://camo.githubusercontent.com/0ea4e18d96d46a06162aafc485c28efa672db0080b7b7b2ba9b68c0754c45e07/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6e656f6d6572782f636f72732d707372372e737667)](https://packagist.org/packages/neomerx/cors-psr7)

Description
-----------

[](#description)

This package has framework-agnostic [Cross-Origin Resource Sharing](http://www.w3.org/TR/cors/) (CORS) implementation. It is compliant with [PSR-7](http://www.php-fig.org/psr/psr-7/) HTTP message interfaces.

Why this package?

- Implementation is based on [CORS specification](http://www.w3.org/TR/cors/).
- Works with [PSR-7 HTTP message interfaces](http://www.php-fig.org/psr/psr-7/).
- Supports debug mode with [PSR-3 Logger Interface](http://www.php-fig.org/psr/psr-3/).
- Flexible, modular and extensible solution.
- High code quality. **100%** test coverage.
- Free software license [Apache 2.0](LICENSE).

Sample usage
------------

[](#sample-usage)

The package is designed to be used as a middleware. Typical usage

```
use Neomerx\Cors\Analyzer;
use Psr\Http\Message\RequestInterface;
use Neomerx\Cors\Contracts\AnalysisResultInterface;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param RequestInterface $request
     * @param Closure          $next
     *
     * @return mixed
     */
    public function handle(RequestInterface $request, Closure $next)
    {
        $cors = Analyzer::instance($this->getCorsSettings())->analyze($request);

        switch ($cors->getRequestType()) {
            case AnalysisResultInterface::ERR_NO_HOST_HEADER:
            case AnalysisResultInterface::ERR_ORIGIN_NOT_ALLOWED:
            case AnalysisResultInterface::ERR_METHOD_NOT_SUPPORTED:
            case AnalysisResultInterface::ERR_HEADERS_NOT_SUPPORTED:
                // return 4XX HTTP error
                return ...;

            case AnalysisResultInterface::TYPE_PRE_FLIGHT_REQUEST:
                $corsHeaders = $cors->getResponseHeaders();
                // return 200 HTTP with $corsHeaders
                return ...;

            case AnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE:
                // call next middleware handler
                return $next($request);

            default:
                // actual CORS request
                $response    = $next($request);
                $corsHeaders = $cors->getResponseHeaders();

                // add CORS headers to Response $response
                ...
                return $response;
        }
    }
}
```

### Settings

[](#settings)

Analyzer accepts settings in `Analyzer::instance($settings)` which must implement `AnalysisStrategyInterface`. You can use default implementation `\Neomerx\Cors\Strategies\Settings` to set the analyzer up.

For example,

```
use Neomerx\Cors\Strategies\Settings;

$settings = (new Settings())
    ->setServerOrigin('https', 'api.example.com', 443)
    ->setPreFlightCacheMaxAge(0)
    ->setCredentialsSupported()
    ->setAllowedOrigins(['https://www.example.com', ...]) // or enableAllOriginsAllowed()
    ->setAllowedMethods(['GET', 'POST', 'DELETE', ...])   // or enableAllMethodsAllowed()
    ->setAllowedHeaders(['X-Custom-Header', ...])         // or enableAllHeadersAllowed()
    ->setExposedHeaders(['X-Custom-Header', ...])
    ->disableAddAllowedMethodsToPreFlightResponse()
    ->disableAddAllowedHeadersToPreFlightResponse()
    ->enableCheckHost();

$cors = Analyzer::instance($settings)->analyze($request);
```

Settings could be cached which improves performance. If you already have settings configured as in the example above you can get internal settings state as

```
/** @var array $dataToCache */
$dataToCache = $settings->getData();
```

Cached state should be used as

```
$settings = (new Settings())->setData($dataFromCache);
$cors     = Analyzer::instance($settings)->analyze($request);
```

Install
-------

[](#install)

```
composer require neomerx/cors-psr7

```

Debug Mode
----------

[](#debug-mode)

Debug logging will provide a detailed step-by-step description of how requests are handled. In order to activate it a [PSR-3 compatible Logger](http://www.php-fig.org/psr/psr-3/) should be set to `Analyzer`.

```
/** @var \Psr\Log\LoggerInterface $logger */
$logger   = ...;

$analyzer = Analyzer::instance($settings);
$analyzer->setLogger($logger)
$cors     = $analyzer->analyze($request);
```

Advanced Usage
--------------

[](#advanced-usage)

There are many possible strategies for handling cross and same origin requests which might and might not depend on data from requests.

This built-in strategy `Settings` implements simple settings identical for all requests (same list of allowed origins, same allowed methods for all requests and etc).

However you can customize such behaviour. For example you can send different sets of allowed methods depending on request. This might be helpful when you have some kind of Access Control System and wish to differentiate response based on request (for example on its origin). You can either implement `AnalysisStrategyInterface` from scratch or override methods in `Settings` class if only a minor changes are needed to `Settings`. The new strategy could be sent to `Analyzer` constructor or `Analyzer::instance` method could be used for injection.

Example

```
class CustomMethodsSettings extends Settings
{
    public function getRequestAllowedMethods(RequestInterface $request): string
    {
        // An external Access Control System could be used to determine
        // which methods are allowed for this request.

        return ...;
    }
}

$cors = Analyzer::instance(new CustomMethodsSettings())->analyze($request);
```

Testing
-------

[](#testing)

```
composer test

```

Questions?
----------

[](#questions)

Do not hesitate to check [issues](https://github.com/neomerx/cors-psr7/issues) or post a new one.

Contributing
------------

[](#contributing)

If you have spotted any compliance issues with the [CORS Recommendation](http://www.w3.org/TR/cors/) please post an [issue](https://github.com/neomerx/cors-psr7/issues). Pull requests for documentation and code improvements (PSR-2, tests) are welcome.

Versioning
----------

[](#versioning)

This package is using [Semantic Versioning](http://semver.org/).

License
-------

[](#license)

Apache License (Version 2.0). Please see [License File](LICENSE) for more information.

###  Health Score

22

—

LowBetter than 23% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 79.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

Unknown

Total

1

Last Release

969d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e34fa12de3febc941b3a1b7dd6dd1c9e2b12cf50ba0576f41deab4acf72ca184?d=identicon)[TXC](/maintainers/TXC)

---

Top Contributors

[![neomerx](https://avatars.githubusercontent.com/u/10420662?v=4)](https://github.com/neomerx "neomerx (43 commits)")[![TXC](https://avatars.githubusercontent.com/u/236697?v=4)](https://github.com/TXC "TXC (9 commits)")[![MrHash](https://avatars.githubusercontent.com/u/390925?v=4)](https://github.com/MrHash "MrHash (1 commits)")[![nikserg](https://avatars.githubusercontent.com/u/5680589?v=4)](https://github.com/nikserg "nikserg (1 commits)")

---

Tags

psr-7corspsr7Cross-Origin Resource Sharingwww.w3.orgw3.orgtxc

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/txc-cors-psr7/health.svg)

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

###  Alternatives

[neomerx/cors-psr7

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

682.4M19](/packages/neomerx-cors-psr7)[league/route

Fast routing and dispatch component including PSR-15 middleware, built on top of FastRoute.

6633.1M116](/packages/league-route)[dflydev/fig-cookies

Cookies for PSR-7 HTTP Message Interface.

2268.5M101](/packages/dflydev-fig-cookies)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

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

CORS (Cross-Origin Resource Sharing) support for Laravel and Lumen

4996.4k2](/packages/neomerx-cors-illuminate)

PHPackages © 2026

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