Skip to content

Instantly share code, notes, and snippets.

@mossy2100
Created December 23, 2014 05:03
Show Gist options
  • Save mossy2100/7a407be7d14809915832 to your computer and use it in GitHub Desktop.
Save mossy2100/7a407be7d14809915832 to your computer and use it in GitHub Desktop.
handy CORS functions
<?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