Created
December 23, 2014 05:03
-
-
Save mossy2100/7a407be7d14809915832 to your computer and use it in GitHub Desktop.
handy CORS functions
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 | |
/** | |
* Get the request origin. | |
* | |
* @return string | |
* The origin of the http request or FALSE if it could not be determined. | |
*/ | |
function vayant_get_origin() { | |
$origin = FALSE; | |
$headers = getallheaders(); | |
if (!empty($headers['Origin'])) { | |
$origin = $headers['Origin']; | |
} | |
if (!$origin && !empty($_SERVER['HTTP_ORIGIN'])) { | |
$origin = $_SERVER['HTTP_ORIGIN']; | |
} | |
if (!$origin && !empty($headers['Host'])) { | |
$origin = $headers['Host']; | |
} | |
if (!$origin && !empty($_SERVER['HTTP_HOST'])) { | |
$origin = $_SERVER['HTTP_HOST']; | |
} | |
return $origin; | |
} | |
/** | |
* Check if the referer is allowed to access this endpoint. | |
* | |
* @return bool | |
* TRUE if the requesting site is allowed to access this service. | |
*/ | |
function vayant_origin_allowed($origin) { | |
// Compare with domains: | |
$domains = require dirname(DRUPAL_ROOT) . '/config/drupal/domains.php'; | |
foreach ($domains as $domain => $config) { | |
// Check if the origin ends in the domain. This will match, e.g. | |
// origin = '*.flightcentre.com' with domain = 'flightcentre.com'. | |
if (substr($origin, -strlen($domain)) == $domain) { | |
return TRUE; | |
} | |
} | |
return FALSE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment