Enable CORS for multiple domains in PHP

In this article, 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://domainXYZ.com
Access-Control-Allow-Origin: null

The above is a simple implementation.

For multiple domains permissions of CORS, we can use a PHP snippet like below:

<?php
$allowedOrigins = [
   'https://domainXYZ.com',
   'https://z1.domainXYZ.com',
   'https://z2.domainXYZ.com',
   'https://z3.domainXYZ.com',
   'http://z4.domainXYZ4.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");
?>