CORS in PHP (Allow Frontend Apps to Call Your API)
Understand CORS and configure safe headers for local dev and production.
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).