cors origin with list domain code example
Example 1: php cors header multiple domains
function CORS_HEADERS_HANDLER(){
if (isset($_SERVER['HTTP_ORIGIN'])){
switch($_SERVER['HTTP_ORIGIN']){
case 'http://1.2.3.4:4200':
header('Access-Control-Allow-Origin: http://1.2.3.4:4200');
break;
case 'https://www.someSite.com':
header('Access-Control-Allow-Origin: https://www.someSite.com');
break;
case 'http://www.someSite.com':
header('Access-Control-Allow-Origin: http://www.someSite.com');
break;
case 'https://not.you':
header('Access-Control-Allow-Origin: https://nice.try');
break;
default:
header('Access-Control-Allow-Origin: https://not.you');
break;
}
}else{
header('Access-Control-Allow-Origin: https://not.you');
}
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json; charset=utf-8');
header("Cache-Control: public,max-age=3600");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
die();
}
}
Example 2: header cross origin using php only for our domains and subdomain
$allowedOrigins = [
"http://www.websiteA.com",
"https://www.websiteB.com"
];
if (in_array($_SERVER["HTTP_ORIGIN"], $allowedOrigins)) {
header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);
}