Library and middleware enabling cross-origin resource sharing (CORS) for your PHP interoperable application, utilizing the PSR-7 and PSR-15 standards.
It attempts to implement the W3C Recommendation for cross-origin resource sharing.
Require compwright/psr-cors
using composer.
This package can be used as a library or as PSR-15 middleware.
Option | Description | Default value |
---|---|---|
allowedMethods |
Matches the request method. | All |
allowedOrigins |
Matches the request origin (supports regex). | All |
allowedHeaders |
Sets the Access-Control-Allow-Headers response header. | All |
exposedHeaders |
Sets the Access-Control-Expose-Headers response header. | None |
maxAge |
Sets the Access-Control-Max-Age response header. Set to null to omit the header/use browser default. |
None |
supportsCredentials |
Sets the Access-Control-Allow-Credentials header. | None |
The allowedMethods and allowedHeaders options are case-insensitive.
If true
is provided to allowedMethods, allowedOrigins or allowedHeaders all methods/origins/headers are allowed.
If supportsCredentials is true
, you must explicitly set allowedHeaders
for any headers which are not CORS safelisted.
<?php
use Compwright\PsrCors\Middleware;
$middleware = Middleware::create(
responseFactory: $psrResponseFactory,
allowedHeaders: ['x-allowed-header', 'x-other-allowed-header'],
allowedMethods: ['DELETE', 'GET', 'POST', 'PUT'],
allowedOrigins: ['localhost'],
exposedHeaders: [],
maxAge: 600,
supportsCredentials: false
);
$response = $middleware->handle($request, $app);