CORS
suggest changeCross-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
- Simple Requests: Basic
GET,HEAD, orPOSTrequests with standard content types (text/plain,application/x-www-form-urlencoded,multipart/form-data) include anOriginheader. The server must respond withAccess-Control-Allow-Origin. - 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 HTTPOPTIONSpreflight request before sending the actual request. The server must acknowledge the preflight request with appropriate permissions and an HTTP204 No Contentor200 OKstatus 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
- 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. - Wildcard (
*) Incompatibility with Credentials: IfAccess-Control-Allow-Credentials: trueis enabled, the browser will reject the response ifAccess-Control-Allow-Originis set to*. You must specify the exact matching domain. - Exit Early on
OPTIONS: Always callexit(0)after sending headers forOPTIONSpreflights so database connections and business logic are not needlessly executed.