PHPPHP16 min read

CORS in PHP (Allow Frontend Apps to Call Your API)

Understand CORS and configure safe headers for local dev and production.

Jacob Miller
Oct 13, 2025
15.4k401

CORS (Cross-Origin Resource Sharing) decides whether a frontend from one origin can call your API from another origin.

Example:

Browser blocks calls unless API allows it.

Basic CORS headers

header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

Handle OPTIONS (preflight)

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(204);
  exit;
}

Security tip

Do not use * for Allow-Origin in authenticated APIs. Be explicit with allowed domains.

Next: JWT in PHP APIs (validate tokens, protect routes).

#PHP#API#Security#Advanced