Last active
May 2, 2019 11:46
-
-
Save groupsky/2c146e923adbef4d33b183bd59ae6b5e to your computer and use it in GitHub Desktop.
php CORS with multi origin support
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 | |
// List of allowed origins, should be in some config place, or even loaded from env | |
$ALLOWED_ORIGINS = array( | |
'http://localhost:8080', | |
'... any other origin', | |
); | |
// Validate request is allowed - should be in every entry file | |
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { | |
// there must be an origin to validate | |
if (!isset($_SERVER['HTTP_ORIGIN'])) exit(0); | |
$origin = $_SERVER['HTTP_ORIGIN']; | |
// only respond to allowed origins | |
if (!in_array($origin, $ALLOWED_ORIGINS)) exit(0); | |
header("Access-Control-Allow-Origin: $origin"); | |
header('Access-Control-Allow-Credentials: true'); | |
header('Access-Control-Max-Age: 86400'); // cache for 1 day | |
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) { | |
// may also be using PUT, PATCH, HEAD etc | |
header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); | |
} | |
// allow all headers | |
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) { | |
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); | |
} | |
// terminate as this is an OPTIONS request - doesn't need actual data | |
exit(0); | |
} | |
// actual request handling goes here ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment