PHPackages                             jarir-ahmed/universal-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. jarir-ahmed/universal-cors

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

jarir-ahmed/universal-cors
==========================

A secure-by-default, framework-agnostic CORS handler for PHP (plain PHP, Yii2, Laravel, Slim).

v1.0.0(1mo ago)014↓87.5%1MITPHPPHP &gt;=7.4

Since Jun 6Pushed 1mo agoCompare

[ Source](https://github.com/jarir2020/jarir-ahmed-universal-cors)[ Packagist](https://packagist.org/packages/jarir-ahmed/universal-cors)[ RSS](/packages/jarir-ahmed-universal-cors/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (1)Versions (2)Used By (1)

universal-cors
==============

[](#universal-cors)

A **secure-by-default**, framework-agnostic CORS handler for PHP. One small class that answers preflight requests and emits the right `Access-Control-*` headers — without the classic footguns (`*` + credentials, blanket origin reflection, forced debug mode).

Why
---

[](#why)

CORS is usually "fixed" by pasting `header("Access-Control-Allow-Origin: *")` plus `Access-Control-Allow-Credentials: true` into a front controller. That combination is forbidden by the spec and lets **any** website call your API with the user's cookies. This package makes the safe path the easy path.

Requirements
------------

[](#requirements)

- PHP &gt;= 7.4

Install
-------

[](#install)

```
composer require jarir-ahmed/universal-cors
```

Usage (plain PHP / any framework)
---------------------------------

[](#usage-plain-php--any-framework)

Put this at the very top of your front controller or API entry point:

```
use JarirAhmed\UniversalCors\Cors;

$cors = new Cors([
    'allowOrigins'     => ['https://app.example.com', 'http://localhost:3000'],
    'allowMethods'     => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
    'allowHeaders'     => ['Content-Type', 'Authorization'],
    'allowCredentials' => true,
    'maxAge'           => 3600,
]);

// Emits headers; returns true if this was a preflight (then stop).
if ($cors->send()) {
    exit;
}

// ... your normal request handling continues here ...
```

Configuration
-------------

[](#configuration)

KeyDefaultNotes`allowOrigins``[]`Exact origins, or `['*']` (only without credentials).`allowOriginPatterns``[]`Wildcard patterns, e.g. `https://*.example.com`. `*` matches one DNS label and never crosses a dot.`allowMethods``GET, POST, PUT, PATCH, DELETE, OPTIONS``allowHeaders``Content-Type, Authorization`Use `['*']` to reflect the browser's requested headers.`exposeHeaders``[]`Response headers JS may read.`allowCredentials``false`When `true`, the matching origin is reflected (never `*`).`maxAge``0`Preflight cache seconds.### Safety guarantees

[](#safety-guarantees)

- `allowOrigins: ['*']` **with** `allowCredentials: true` throws on construction.
- With credentials, the request `Origin` is **reflected** for allowed origins — never a blanket `*` — and `Vary: Origin` is set for correct caching.
- Unlisted origins receive **no** `Access-Control-Allow-Origin` header, so the browser blocks the response.

Testing without sending headers
-------------------------------

[](#testing-without-sending-headers)

`resolve()` and `handle()` are pure and return a `CorsResult` you can assert on:

```
$result = $cors->handle($_SERVER);     // or resolve($origin, $method, $requestHeaders)
$result->headers;       // array of response headers
$result->isPreflight;   // bool
$result->status;        // 204 for a preflight to short-circuit, else null
$result->isAllowed();   // whether an Allow-Origin header was produced
```

Framework notes
---------------

[](#framework-notes)

- **Plain PHP / Slim / custom**: call `$cors->send()` early; `exit` on preflight.
- **Yii2**: prefer the built-in `yii\filters\Cors` behavior; use this package when you want one consistent CORS policy across non-Yii entry points too.
- **Laravel**: register `send()` in a global middleware's `handle()` before the app runs.

License
-------

[](#license)

MIT

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance90

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

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

49d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/20700f34ff813055154e843bbdbe04d33320c1e6a81bbb3301cad67cb8350fd3?d=identicon)[jarircse16](/maintainers/jarircse16)

---

Tags

httpmiddlewareapisecuritycorspreflight

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jarir-ahmed-universal-cors/health.svg)

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

###  Alternatives

[chadicus/slim-oauth2

OAuth2 routes, middleware and utilities for use within a Slim Framework API

129376.3k4](/packages/chadicus-slim-oauth2)[middlewares/cors

Middleware to implement Cross-Origin Resource Sharing (CORS)

1375.0k3](/packages/middlewares-cors)[middlewares/referrer-spam

Middleware to block referrer spammers

1159.8k4](/packages/middlewares-referrer-spam)[middlewares/csp

Middleware to add the Content-Security-Policy header to the response

1524.0k](/packages/middlewares-csp)[elementaryframework/water-pipe

URL routing framework and requests/responses handler for PHP

255.2k4](/packages/elementaryframework-water-pipe)[middlewares/honeypot

Middleware to implement a honeypot spam prevention

142.6k](/packages/middlewares-honeypot)

PHPackages © 2026

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