Make an array containing all your allowed origins (you could even keep this in a database or config file if you need to modify it often, so it’s more configurable, and just load it into your PHP array as needed). Then, check if the incoming origin matches one of them. If so, add the Access-Control-Allow-Origin
header accordingly. If not, don’t output that header.
You don’t really need the “denied” response as such – if it’s indeed a CORS request the browser will take care of that and issue a CORS error to the JS code if the returned Access-Control-Allow-Origin
header doesn’t match the origin, or the header is missing.
$allowedOrigins = [
"https://example1.com",
"https://example2.com",
"https://example3.com",
"https://example4.com"
];
if (in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins)) {
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
}
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
N.B. I’m not quite sure what you are trying to achieve by also checking the REFERER header – it’s easy to spoof, and has nothing to do with CORS. I doubt it will help you with whatever goal you had in mind.