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

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

phputil/cors
============

CORS middleware for phputil/router

v0.5.3(1y ago)2659MITPHPCI passing

Since Jan 21Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/thiagodp/cors)[ Packagist](https://packagist.org/packages/phputil/cors)[ RSS](/packages/phputil-cors/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (4)Versions (21)Used By (0)

![Packagist Version](https://camo.githubusercontent.com/9fa5ee93d74a4a7e4c5e092cb1199f77f41d740ed7be96efceb1e803c93ec87b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068707574696c2f636f72733f7374796c653d666f722d7468652d626164676526636f6c6f723d677265656e)[![GitHub License](https://camo.githubusercontent.com/d5d1067599ae39546baec6488494250c8daacaa99d42021d15406ce326287882/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f74686961676f64702f636f72733f7374796c653d666f722d7468652d626164676526636f6c6f723d677265656e)](https://camo.githubusercontent.com/d5d1067599ae39546baec6488494250c8daacaa99d42021d15406ce326287882/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f74686961676f64702f636f72733f7374796c653d666f722d7468652d626164676526636f6c6f723d677265656e)[![Packagist Downloads](https://camo.githubusercontent.com/89e726cb43d921d0a1cfbc1fdc9dd4fb313c65bc66ffdd1ace9c63f0febfc241/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7068707574696c2f636f72733f7374796c653d666f722d7468652d626164676526636f6c6f723d677265656e)](https://camo.githubusercontent.com/89e726cb43d921d0a1cfbc1fdc9dd4fb313c65bc66ffdd1ace9c63f0febfc241/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7068707574696c2f636f72733f7374796c653d666f722d7468652d626164676526636f6c6f723d677265656e)[![Build](https://github.com/thiagodp/cors/actions/workflows/ci.yml/badge.svg?style=for-the-badge&color=green)](https://github.com/thiagodp/cors/actions/workflows/ci.yml/badge.svg?style=for-the-badge&color=green)

phputil/cors
============

[](#phputilcors)

> 🔌 CORS middleware for [phputil/router](https://github.com/thiagodp/router)

- Unit-tested ✔
- Well-documented 📖
- Syntax compatible with [expressjs/cors](https://github.com/expressjs/cors) 🎯

Installation
------------

[](#installation)

> Requires phputil/router **v0.2.14+**

```
composer require phputil/cors
```

*Is it useful for you? Consider giving it a Star ⭐*

Examples
--------

[](#examples)

### Basic usage

[](#basic-usage)

> Enable *all* CORS requests

```
require_once 'vendor/autoload.php';
use phputil\router\Router;
use function phputil\cors\cors; // Step 1: Declare the usage.

$app = new Router();

$app->use( cors() ); // Step 2: Invoke the function to use it as a middleware.

$app->get( '/', function( $req, $res ) {
    $res->send( 'Hello' );
} );

$app->listen();
```

### Accepting credentiais and authorized domains

[](#accepting-credentiais-and-authorized-domains)

> Accepting credentials (e.g. cookies) and cross-site requests from authorized domains:

```
// ...
$options = [
    'origin'            => [ 'https://my-app.com', 'https://authorized-domain.com' ],
    'credentials'       => true,
    'allowedHeaders'    => [ 'Accept', 'Authorization', 'Cookie', 'Content-Length', 'Content-Type', 'Host', 'Origin', 'Referer' ],
    'exposeHeaders'     => [ 'Content-Length', 'Content-Type', 'Set-Cookie' ],
    'maxAge'            => 3600 // Cache Preflight requests for 1 hour
];

$app->use( cors( $options ) );
// ...
```

API
---

[](#api)

```
function cors( array|CorOptions $options ): callable;
```

`$options` can be an **array** or an **object** from the class `CorOptions`.

Example with an array:

```
$options = [
    'origin' => 'mydomain.com',
    'methods' => 'GET,POST'
];

$app->use( cors( $options ) );
```

Example that uses `CorOptions`, a class with chainable methods:

```
use phputil\cors\CorsOptions; // Needed

$options = ( new CorsOptions() )
    ->withOrigin( 'mydomain.com' )
    ->withMethods( 'GET,POST' );

$app->use( cors( $options ) );
```

All `$options`' keys/attributes are **optional**:

### `origin: bool|string|string[]`

[](#origin-boolstringstring)

- Configures the response header [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin), which indicates the allowed origin.
- `true`, **the default value**, reflects the `Origin` request header - that is, it **allows any origin**.
- `false` makes it to return `'*'` as the header value.
- A non-empty `string` (e.g. `'https://example.com'`) restricts the origin to the defined value. An origin must contain the protocol (e.g. `http`/`https`), and the port (e.g. `:8080`) when the port is different from the default for the protocol (`80` for http, `443` for https).
- A non-empty `array` indicates the list of allowed origins.
- When the `Origin` request header *is not sent* and the option `origin` is `true`, it will return `*` - aiming to accept any origin (which may not work on httpS or using credentials). Other options will block the request.
- Using `*` will probably not work when using credentials or httpS. Therefore, make sure to include the allowed origins.

Note: The status code returned for an origin that is not in the allowed list is `403` (Forbidden).

### `credentials: bool`

[](#credentials-bool)

- Configures the response header [`Access-Control-Allow-Credentials`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials).
- `true`, **the default value**, makes it to include the header.
- `false` makes it to omit the header.
- This option is needed if your application uses cookies or some kind of authentication header.
- *Bonus tip*: If you are using `fetch()` in your front-end (JavaScript), make sure to set `credentials: 'include'` (when cross-origin) or `credentials: 'same-origin` to your request options.

### `methods: string|string[]`

[](#methods-stringstring)

- Configures the response header [`Access-Control-Allow-Methods`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods).
- The **default value** is `GET,HEAD,OPTIONS,POST,PUT,DELETE,PATCH` when the request header `Access-Control-Request-Method` is *not* defined.
- When the request header `Access-Control-Request-Method` is defined, the response header `Access-Control-Allow-Methods` will return the received method, unless the option `methods` is defined.
- HTTP methods in a `string` must be separated by **comma**.

### `allowedHeaders: string|string[]`

[](#allowedheaders-stringstring)

- Configures the response header [`Access-Control-Allow-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers).
- The **default value** is `'*'`, meaning to accept any request header.
- The value `*` only counts as a special wildcard value for requests without credentials (e.g. cookies, authorization headers). Therefore, change it if your application needs credentials.
- HTTP headers in a `string` must be separated by **comma**.

### `exposedHeaders: string|string[]`

[](#exposedheaders-stringstring)

- Configures the response header [`Access-Control-Expose-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers).
- The **default value** is `''` (empty string), meaning to not include the header.
- HTTP headers in a `string` must be separated by **comma**.
- If your application needs credentials (e.g. cookies, authentication headers), you probably should configure it.

### `maxAge: int|null`

[](#maxage-intnull)

- Configures the response header [`Access-Control-Max-Age`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age).
- The **default value** is `null`, meaning to not include the header.
- An `int` value means the number of seconds that a preflight request can be cached (by the browser).

License
-------

[](#license)

[MIT](LICENSE) © [Thiago Delgado Pinto](https://github.com/thiagodp)

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance67

Regular maintenance activity

Popularity19

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

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

Recently: every ~79 days

Total

18

Last Release

419d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/154324d722a6ee9c252a0338329781084a97af2d0ea9faaf39176df5a689a2ec?d=identicon)[thiagodp](/maintainers/thiagodp)

---

Top Contributors

[![thiagodp](https://avatars.githubusercontent.com/u/2997844?v=4)](https://github.com/thiagodp "thiagodp (51 commits)")

---

Tags

corsexpressphprouter

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[php-http/cache-plugin

PSR-6 Cache plugin for HTTPlug

25126.1M82](/packages/php-http-cache-plugin)[illuminate/http

The Illuminate Http package.

11937.9M6.9k](/packages/illuminate-http)[rdkafka/rdkafka

A PHP extension for Kafka

2.2k24.3k1](/packages/rdkafka-rdkafka)[httpsoft/http-message

Strict and fast implementation of PSR-7 and PSR-17

87965.9k114](/packages/httpsoft-http-message)[mezzio/mezzio-router

Router subcomponent for Mezzio

265.4M92](/packages/mezzio-mezzio-router)[serpapi/google-search-results-php

Get Google, Bing, Baidu, Ebay, Yahoo, Yandex, Home depot, Naver, Apple, Duckduckgo, Youtube search results via SerpApi.com

69127.2k](/packages/serpapi-google-search-results-php)

PHPackages © 2026

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