CORS

suggest change

Cross-Origin Resource Sharing (CORS) is an HTTP-header-based security mechanism implemented by web browsers. It restricts client-side scripts running at one origin (domain, protocol, or port) from making requests to a different origin. When building REST APIs or single-page application (SPA) backends in PHP, you must configure CORS headers so client applications (React, Vue, Angular, mobile web views) can access your endpoints.


1. How CORS Works

  1. Simple Requests: Basic GET, HEAD, or POST requests with standard content types (text/plain, application/x-www-form-urlencoded, multipart/form-data) include an Origin header. The server must respond with Access-Control-Allow-Origin.
  2. Preflighted Requests: Requests sending custom headers (e.g. Authorization, X-Requested-With), JSON payloads (application/json), or mutating verbs (PUT, PATCH, DELETE) trigger an automated HTTP OPTIONS preflight request before sending the actual request. The server must acknowledge the preflight request with appropriate permissions and an HTTP 204 No Content or 200 OK status before the browser sends the real payload.

2. Complete PHP CORS Handler

Here is a robust, production-ready CORS handler supporting dynamic allowlists, preflight responses, credentials, and custom headers:

<?php

function handleCors(array $allowedOrigins = []): void
{
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '';

    // 1. Verify Origin against allowlist
    if (in_array($origin, $allowedOrigins, true)) {
        header("Access-Control-Allow-Origin: $origin");
        header("Access-Control-Allow-Credentials: true");
    } elseif (empty($allowedOrigins)) {
        // Public open API (credentials not supported with wildcard)
        header("Access-Control-Allow-Origin: *");
    } else {
        // Disallowed origin: do not emit CORS headers
        return;
    }

    // Set allowed methods and headers
    header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-API-Key");
    header("Access-Control-Max-Age: 86400"); // Cache preflight for 24 hours

    // 2. Intercept and terminate preflight OPTIONS requests immediately
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(204); // No Content
        header("Content-Length: 0");
        exit(0);
    }
}

// Usage at application bootstrap (e.g. index.php)
$allowedDomains = [
    'https://app.example.com',
    'https://staging.example.com',
    'http://localhost:3000', // Local frontend development
];

handleCors($allowedDomains);

// Remainder of your API logic:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'API ready']);

3. Key CORS Response Headers

Header Description Example
Access-Control-Allow-Origin Specifies which origin(s) can access the resource. https://example.com or *
Access-Control-Allow-Methods Comma-delimited list of permitted HTTP methods. GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers Request headers allowed during the actual request. Content-Type, Authorization
Access-Control-Allow-Credentials Informs browser whether response can be exposed when credentials (cookies, HTTP auth) are sent. true
Access-Control-Max-Age Number of seconds the preflight response can be cached by the browser to avoid repeated OPTIONS calls. 86400 (24 hours)
Access-Control-Expose-Headers Exposes custom response headers to client JavaScript. X-Total-Count, X-RateLimit-Remaining

4. Exposing Custom Headers to JavaScript

By default, browser JavaScript (fetch() or axios) can only inspect basic CORS-safelisted response headers (Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, Pragma).

If your API sends pagination or rate-limiting headers, you must explicitly expose them using Access-Control-Expose-Headers:

<?php

header("Access-Control-Expose-Headers: X-Total-Count, X-Page-Count");
header("X-Total-Count: 1542");
header("X-Page-Count: 16");

5. Web Server-Level Configuration (Nginx & Apache)

Handling CORS at the web server level (before reaching PHP-FPM) improves performance for preflight requests:

Nginx

location /api/ {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '$http_origin' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, PATCH, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, X-Requested-With' always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Max-Age' 86400;
        add_header 'Content-Length' 0;
        return 204;
    }

    try_files $uri $uri/ /index.php?$query_string;
}

Security Best Practices

  1. Never Blindly Echo Incoming Origin: Avoid header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']) without validation against an allowlist. This effectively disables browser Same-Origin Policy protection for all domains on the internet.
  2. Wildcard (*) Incompatibility with Credentials: If Access-Control-Allow-Credentials: true is enabled, the browser will reject the response if Access-Control-Allow-Origin is set to *. You must specify the exact matching domain.
  3. Exit Early on OPTIONS: Always call exit(0) after sending headers for OPTIONS preflights so database connections and business logic are not needlessly executed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents