PHPPHP18 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
October 11, 2025
3.7k168

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