How to Enable CORS for multiple domains in PHP
In this tutorial we will explain how to permit CORS requests for multiple origins in PHP.
To get the response from a simple cross-origin POST request, we need to include the header Access-Control-Allow-Origin. The specification of Access-Control-Allow-Origin allows for multiple origins, or the value null, or the wildcard *.
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: https:mydomain.com
Access-Control-Allow-Origin: null
Check the following code to enable CORS for multiple domains.
$allowedOrigins = [
'https://example.com',
'https://staging.example.com' ,
'https://production.example.com' ,
];
if(in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins))
{
$http_origin = $_SERVER['HTTP_ORIGIN'];
} else {
$http_origin = "https://example.com";
}
header("Access-Control-Allow-Origin: $http_origin");
In the above code, we have taken an array of multiple domains which we want to allow in Access-Control-Allow-Origin.
Use the $_SERVER['HTTP_ORIGIN'] variable to verify which domain the request comes from and then conditionally set the Access-Control-Allow-Origin.