Created
October 15, 2013 13:49
-
-
Save renoirb/6991866 to your computer and use it in GitHub Desktop.
CORS header modification using PHP
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 | |
/** | |
* 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