Last active
September 4, 2020 01:41
-
-
Save summersab/64f8d027248bdb5a08ca90de0fd2442c to your computer and use it in GitHub Desktop.
CORS Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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