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

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

sankaest/neomerx-cors-psr7
==========================

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

v1.0.2(3y ago)05Apache-2.0PHPPHP ^7.1|^8.0

Since Jun 16Pushed 3y ago1 watchersCompare

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

READMEChangelog (1)Dependencies (8)Versions (4)Used By (0)

[![Build Status](https://camo.githubusercontent.com/c1cee4579a4ee6ce04f0638b6b013499eb1b94aec207c100609fd8ccc66eb9e0/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73616e6b616573742f6e656f6d6572782d636f72732d707372372f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/sankaest/neomerx-cors-psr7/badges/build.png?b=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/31864979949a0076319a7ae27b267bd089268b980b5661a6ddc657ab88d3c3f1/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73616e6b616573742f6e656f6d6572782d636f72732d707372372f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/sankaest/neomerx-cors-psr7/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/78b70e64fa58d50dd33d65adabe5fc721141f8fd368a987146f27bf8fbbf42a3/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f73616e6b616573742f6e656f6d6572782d636f72732d707372372f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/sankaest/neomerx-cors-psr7/?branch=master)[![License](https://camo.githubusercontent.com/8b93d6db8904047931f5b065aa2e151fced3e42f160d63edb8380d88a0fe1f8c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73616e6b616573742f6e656f6d6572782d636f72732d707372372e737667)](https://packagist.org/packages/sankaest/neomerx-cors-psr7)

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

[](#description)

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

Why this package?

- Implementation is based on latest [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 sankaest/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/sankaest/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/sankaest/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

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

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

Total

3

Last Release

1427d ago

PHP version history (2 changes)v1.0.0PHP &gt;=7.1.0

v1.0.1PHP ^7.1|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/826d3c778d6839730cf4eda440955d48d4eea30a52a06e16791636809df5f5a1?d=identicon)[sankaest](/maintainers/sankaest)

---

Top Contributors

[![sankaest](https://avatars.githubusercontent.com/u/21160342?v=4)](https://github.com/sankaest "sankaest (7 commits)")

---

Tags

psr-7corspsr7neomerxCross-Origin Resource Sharingwww.w3.orgw3.org

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/sankaest-neomerx-cors-psr7/health.svg)](https://phpackages.com/packages/sankaest-neomerx-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.1M115](/packages/league-route)[dflydev/fig-cookies

Cookies for PSR-7 HTTP Message Interface.

2268.5M102](/packages/dflydev-fig-cookies)[neomerx/cors-illuminate

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

4996.4k2](/packages/neomerx-cors-illuminate)[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)

PHPackages © 2026

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