Skip to content

Instantly share code, notes, and snippets.

@renoirb
Created October 15, 2013 13:49
Show Gist options
  • Save renoirb/6991866 to your computer and use it in GitHub Desktop.
Save renoirb/6991866 to your computer and use it in GitHub Desktop.
CORS header modification using PHP
<?php
/**
* CORS header manipulation handler
*
* This utility will add header in the
* HTTP response and help us execute JavaScript
* from differen sub-domains.
*
* @author Renoir Boulanger <renoir@w3.org>
**/
/**
* List domain names that are allowed to be accessed cross-origin
*
* @var array
*/
$allowedHosts = array(
'docs.webplatform.org',
'blog.webplatform.org'
);
// Initial values
$protocol = 'http';
$allowed_referer_pass = false;
// MUST have h GET parameter, matching $allowedHosts array
// We also will use this variable to set appropriate Access-Control* HTTP header
// If it returns bool false, it is fine, since the hostname will obviously make the XHR fail anyway
$allowed_hostname = (in_array($_GET['h'], $allowedHosts))?$_GET['h']:FALSE;
header('Access-Control-Allow-Origin: '.$protocol.'://'.$allowed_hostname);
// MUST have a referrer, and be part of $allowedHosts array
if(!empty($_SERVER['HTTP_REFERER'])) {
$allowed_referer_pass = (in_array(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST), $allowedHosts))?true:false;
}
// If ANY of the two tests fails, we block everything
if($allowed_referer_pass === FALSE || $allowed_hostname === FALSE){
header('HTTP/1.1 412 Precondition Failed');
die('Disallowed host');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment