Download the PHP package effectra/cors without Composer

On this page you can find all versions of the php package effectra/cors. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package cors

effectra/cors

A PHP library for handling Cross-Origin Resource Sharing (CORS) in HTTP applications. Built on PSR-7, PSR-15, and PSR-17 standards, it provides a flexible middleware and a standalone service class that can be integrated into any PHP project or framework.

Features


Requirements


Installation


Quick Start


Classes

CorsService

The core CORS engine. Inspects requests, validates origins, and injects the appropriate CORS response headers.

Constructor

Optionally pass a configuration array at construction time. The same array can be applied later via setOptions().


Configuration Options

Key (camelCase) Key (snake_case) Type Default Description
allowedOrigins allowed_origins string[] [] Exact origins allowed. Use ['*'] to allow all.
allowedOriginsPatterns allowed_origins_patterns string[] [] Regex-style wildcard patterns, e.g. ['https://*.example.com'].
allowedMethods allowed_methods string[] [] HTTP methods to allow. Use ['*'] to allow all.
allowedHeaders allowed_headers string[] [] Request headers to allow. Use ['*'] to allow all.
exposedHeaders exposed_headers string[] [] Response headers the browser may read.
supportsCredentials supports_credentials bool false Allow cookies/auth. Incompatible with allowedOrigins: ['*'].
maxAge max_age int\|null 0 Preflight cache duration in seconds. null omits the header entirely.

Note: Both camelCase and snake_case keys are accepted everywhere.


Public Methods

setOptions(array $options): void

Apply (or re-apply) a configuration array. Validates all values before storing them and throws InvalidArgumentException on invalid input.


setDebugMode(bool $debug): self

Enable debug mode. When active, CORS errors are written to the PHP error log and exceptions are re-thrown instead of being swallowed.


isCorsRequest(RequestInterface $request): bool

Returns true when the request carries a non-empty Origin header — the sign of a cross-origin request.


isPreflightRequest(RequestInterface $request): bool

Returns true when the request is an OPTIONS preflight — i.e., the method is OPTIONS and Access-Control-Request-Method is present.


isOriginAllowed(RequestInterface $request): bool

Checks whether the request Origin is permitted by the current configuration. Supports exact matches and wildcard patterns. Also validates the origin URL format.


handlePreflightRequest(RequestInterface $request): ResponseInterface

Builds and returns a complete preflight response (204 No Content on success, 403 Forbidden when the origin is not allowed). Delegates header injection to addPreflightRequestHeaders().


addPreflightRequestHeaders(ResponseInterface $response, RequestInterface $request): ResponseInterface

Injects all relevant preflight headers into an existing response:

Returns the response unchanged when the origin is not allowed.


addActualRequestHeaders(ResponseInterface $response, RequestInterface $request): ResponseInterface

Injects CORS headers for a real (non-preflight) request:


varyHeader(ResponseInterface $response, string $header): ResponseInterface

Appends a value to the Vary response header without creating duplicates. Used internally to ensure correct caching behaviour when the origin or method varies per-request.


getErrors(): array

Returns all CORS errors collected during the current request cycle, keyed by error type (origin, method, preflight, configuration, etc.).


hasErrors(): bool

Returns true if any CORS errors have been recorded.


clearErrors(): void

Resets the internal error collection. Useful when reusing the service across multiple requests in long-running processes.


CorsMiddleware

A PSR-15 middleware that wraps CorsService and integrates it into a request/response pipeline.

Constructor

Config Key Type Default Description
paths / allowed_paths string[] [] Paths CORS is applied to. Empty means all paths.
excluded_paths string[] [] Paths where CORS processing is skipped entirely.
handle_preflight bool true Whether to handle OPTIONS preflight requests automatically.
handle_errors bool true Whether to catch exceptions and expose errors via header.

process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

The PSR-15 entry point. Execution flow:

  1. Skip — if the request is not a CORS request, or the path is excluded / not in the allowlist, the request passes through to the next handler unchanged.
  2. Preflight — if handle_preflight is true and the request is a preflight OPTIONS, a complete preflight response is returned immediately (without calling the next handler).
  3. Actual request — the next handler is called and CORS headers are added to its response.
  4. Error header — if handle_errors is true and errors were collected, they are serialised into X-CORS-Errors as JSON.
  5. Exception safety — uncaught exceptions return a 500 response with CORS headers when handle_errors is true; otherwise they are re-thrown.

Fluent Setter Methods

All setters return $this for method chaining.

setPaths(array $paths): self

Set (or replace) the list of paths CORS should be applied to.


setExcludedPaths(array $paths): self

Set (or replace) the list of paths to exclude from CORS handling.


setHandlePreflight(bool $handle): self

Enable or disable automatic preflight handling.


setHandleErrors(bool $handle): self

Enable or disable graceful error handling. When disabled, exceptions propagate normally.


getCorsService(): CorsService

Returns the underlying CorsService instance — useful for inspecting errors after a request.


Path Matching

Both paths and excluded_paths support three matching strategies:

Pattern Example Matches
Exact api/users /api/users only
Wildcard * api/* /api/users, /api/posts, …
Single char ? v?/resource /v1/resource, /v2/resource

Paths can also be scoped to a specific hostname by using the hostname as the array key:


Origin Validation

CorsService validates the origin format before checking allow-lists:

Wildcard patterns in allowedOrigins (e.g. https://*.example.com) are automatically compiled to regex and matched against each incoming request origin.


Credential-Aware Enforcement

When supportsCredentials is true:


Error Handling

Errors are collected internally rather than silently discarded:

When handle_errors is enabled on CorsMiddleware, all collected errors are exposed via the X-CORS-Errors response header as a JSON string.


Advanced Examples

Allow all origins (public API)

Subdomain wildcard

Restrict CORS to specific routes

Fluent configuration

Standalone usage (without a middleware stack)


Response Headers Reference

Header Set by Condition
Access-Control-Allow-Origin Preflight & actual request Origin is allowed
Access-Control-Allow-Credentials Preflight & actual request supportsCredentials is true
Access-Control-Allow-Methods Preflight only Origin is allowed
Access-Control-Allow-Headers Preflight only Origin is allowed
Access-Control-Max-Age Preflight only maxAge is not null
Access-Control-Expose-Headers Actual request exposedHeaders is non-empty
Vary Both Dynamic origin or method matching is active
X-CORS-Errors Middleware Errors collected and handle_errors is enabled

Contributing

Contributions are welcome! Please open an issue or submit a pull request. For major changes, open an issue first to discuss what you would like to change.


License

The effectra/cors package is open-sourced software licensed under the MIT license.


All versions of cors with dependencies

PHP Build Version
Package Version
Requires psr/http-message Version ^2.0@dev
psr/http-server-handler Version ^1.0@dev
psr/http-server-middleware Version ^1.0@dev
effectra/http-message Version ^1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package effectra/cors contains the following files

Loading the files please wait ...