Skip to content

Instantly share code, notes, and snippets.

@summersab
Last active September 4, 2020 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save summersab/64f8d027248bdb5a08ca90de0fd2442c to your computer and use it in GitHub Desktop.
Save summersab/64f8d027248bdb5a08ca90de0fd2442c to your computer and use it in GitHub Desktop.
CORS Function
<?php
$allowedOrigins = [
'https://domain.com',
'https://www.domain.com',
'https://subdomain.domain.com',
'*',
];
$origin = cors($allowedOrigins, 'GET, POST');
function cors($allowedOrigins, $methods) {
if (function_exists('getallheaders') && isset(getallheaders()['Origin'])) {
$origin = getallheaders()['Origin'];
}
else if (isset($_SERVER['HTTP_ORIGIN'])) {
$origin = $_SERVER['HTTP_ORIGIN'];
}
else if (isset($_SERVER['argv'][0]) && $_SERVER['argv'][0] == basename(__FILE__)) {
$origin = 'http://localhost';
}
else {
echo 'ERROR: origin header not set.';
die;
}
$permitted = 0;
foreach ($allowedOrigins as $allowedOrigin) {
if ($allowedOrigin == '*' || preg_match('#' . $allowedOrigin . '#', $origin)) {
header('Access-Control-Allow-Origin: ' . $origin);
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, Origin, X-Auth-Token, X-Requested-With');
$permitted = 1;
break;
}
}
if (!$permitted) {
echo 'ERROR: origin ' . $origin . ' not permitted.';
die;
}
return $origin;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment