API Security

Handle CORS Correctly in PHP APIs

Configure cross-origin access with explicit origins, methods and headers while understanding what CORS does not protect.

Overview

Cross-Origin Resource Sharing (CORS) is a browser mechanism that controls whether frontend code from one origin may read a response from another origin. It is not authentication and does not stop direct requests from scripts, servers or command-line clients.

Use an origin allow-list

Do not reflect any incoming Origin value into Access-Control-Allow-Origin. Compare it against a fixed list and return only an approved origin.

$allowedOrigins = [
    'https://app.example.com',
    'https://admin.example.com',
];

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins, true)) {
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Vary: Origin');
}

If credentials are required, the allowed origin must be explicit; wildcard * cannot be combined with credentialed browser requests. Set Access-Control-Allow-Credentials: true only when the application genuinely needs cookies or other browser credentials.

Handle preflight requests

Browsers may send an OPTIONS request before the actual request. Respond with only the methods and headers your API supports. Do not treat a successful preflight as authorization for the later request.

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    header('Access-Control-Max-Age: 600');
    http_response_code(204);
    exit;
}

Place CORS handling early enough that errors and preflight responses receive consistent headers. Avoid allowing every method and header by default.

CORS and CSRF

If browser cookies authenticate requests, evaluate CSRF protections separately. CORS does not prevent every cross-site request from being sent; it primarily governs whether browser scripts can read responses. Use appropriate SameSite cookie settings, CSRF tokens and origin checks for state-changing actions.

Checklist

  • Maintain an explicit origin allow-list.
  • Never blindly reflect arbitrary origins.
  • Keep credentialed CORS narrow.
  • Handle OPTIONS consistently.
  • Allow only required methods and headers.
  • Implement authentication, authorization and CSRF defenses independently.

References

MDN CORS · OWASP CSRF Prevention

Share this page Help other developers discover this resource.