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
December 21, 2025
0.0k0

CORS (Cross-Origin Resource Sharing) decides whether a frontend from one origin can call your API from another origin. Example: - frontend: http://localhost:3000 - api: http://localhost:8000 Browser blocks calls unless API allows it. ## Basic CORS headers ```php 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) ```php 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