Specify Multiple Subdomains with Access Control Origin

Here's how I did it.

The Origin header is specified by the browser and will contain the domain that requested the script on the other domain:

Origin: http://www.websiteA.com

Therefore you can "whitelist" multiple domains in your server-side script:

$allowedOrigins = [
    "http://www.websiteA.com",
    "https://www.websiteB.com"
    // ... etc
];

What you can then do is check if the $_SERVER["HTTP_ORIGIN"] global contains a domain within that whitelist:

if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {

And set the Access-Control-Allow-Origin response header to whatever Origin header value was:

header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);

Full script:

$allowedOrigins = [
    "http://www.websiteA.com",
    "https://www.websiteB.com"
    // ... etc
];

if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {
    header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);
}

The solution to this issue is to use the $_SERVER['HTTP_ORIGIN'] variable to determine whether the request has come from an allowed domain, and then conditionally set the Access-Control-Allow-Origin like so:

$allowed_domains = [/* Array of allowed domains*/];

if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}