How to allow requests from another site (CORS)
Short answer
A browser lets JavaScript from another site read the response only if the server sends a header:
<?php
header('Access-Control-Allow-Origin: https://app.example.com');
header('Content-Type: application/json');
echo json_encode(['ok' => true]);Several allowed sites
Compare the Origin header with your list:
<?php
$allowed = ['https://app.example.com', 'https://admin.example.com'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowed, true)) {
header('Access-Control-Allow-Origin: ' . $origin);
header('Vary: Origin');
}The preflight request
Before requests with JSON or an Authorization header the browser sends an OPTIONS request. It is answered with headers and no body:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
http_response_code(204);
exit;
}Functions used in this recipe
- header — Sends an HTTP response header.
- http_response_code — Sets or returns the response status code.
- in_array — Checks whether a value exists in an array.