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

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

enjoys/cors-psr7
================

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

1.0.0(1mo ago)01Apache-2.0PHPPHP &gt;=8.0.0

Since Apr 30Pushed 1mo agoCompare

[ Source](https://github.com/Enjoyzz/cors-psr7)[ Packagist](https://packagist.org/packages/enjoys/cors-psr7)[ Docs](https://github.com/neomerx/cors-psr7)[ RSS](/packages/enjoys-cors-psr7/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (1)Dependencies (7)Versions (2)Used By (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

36

—

LowBetter than 79% of packages

Maintenance92

Actively maintained with recent releases

Popularity1

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 91.5% 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

40d ago

### Community

Maintainers

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

---

Top Contributors

[![neomerx](https://avatars.githubusercontent.com/u/10420662?v=4)](https://github.com/neomerx "neomerx (43 commits)")[![Enjoyzz](https://avatars.githubusercontent.com/u/1448659?v=4)](https://github.com/Enjoyzz "Enjoyzz (2 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-7corspsr7neomerxCross-Origin Resource Sharingwww.w3.orgw3.org

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[neomerx/cors-psr7

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

682.5M22](/packages/neomerx-cors-psr7)[symfony/symfony

The Symfony PHP framework

31.4k86.9M2.2k](/packages/symfony-symfony)[guzzlehttp/psr7

PSR-7 message implementation that also provides common utility methods

7.9k1.1B3.7k](/packages/guzzlehttp-psr7)[cakephp/cakephp

The CakePHP framework

8.8k19.1M1.7k](/packages/cakephp-cakephp)[tempest/framework

The PHP framework that gets out of your way.

2.2k31.1k11](/packages/tempest-framework)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28146.3k](/packages/phpro-http-tools)

PHPackages © 2026

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