Enable CORS for multiple domains in PHP
Today, weโll explain to you 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
Checkout more articles on PHP
- How to get Title and Meta tags from URL using PHP
- Generate QR code using PHP
- Load dynamic content in Bootstrap Modal with AJAX, PHP and MySQL
- Google reCAPTCHA v3 in PHP
- Calculate the age from date of birth in PHP
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`.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐