Skip to content

Instantly share code, notes, and snippets.

@niksudan
Created June 26, 2015 14:39
Show Gist options
  • Save niksudan/3f5f9c05aefd046adbef to your computer and use it in GitHub Desktop.
Save niksudan/3f5f9c05aefd046adbef to your computer and use it in GitHub Desktop.
Cross Origin Permissions [PHP]
<?php
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // Cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
// Validate the origin
if (true) {
$allowed_origins = array('localhost'); // Enter allowed sites here
$allowed = false;
if (isset($_SERVER['HTTP_ORIGIN'])) {
foreach ($allowed_origins as $allowed_origin) {
if (strpos($_SERVER['HTTP_ORIGIN'], $allowed_origin) !== FALSE) {
$allowed = true;
break;
}
}
}
if (!isset($_SERVER['HTTP_ORIGIN']) || !$allowed) {
header('HTTP/1.0 404 Not Found');
exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment