Clue Mediator

Enable CORS for multiple domains in PHP

๐Ÿ“…July 19, 2021
๐Ÿ—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

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..!! ๐Ÿ™‚