Created
November 17, 2023 17:33
-
-
Save Yalme/120981d3e66bf107cf49cb37512e0eea to your computer and use it in GitHub Desktop.
PHP CORS Access Control Cross-Origin Header
This file contains hidden or 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 | |
// if you want pass all | |
header('Access-Control-Allow-Origin: *'); | |
// if you want limit by domain | |
header('Access-Control-Allow-Origin: https://domain.com'); | |
// if you want limit by multiple domains | |
// list of allowed domains | |
$allowed_domains = array( | |
'domain.com', | |
'domain2.com' | |
); | |
// find out current incoming client | |
if (array_key_exists('HTTP_ORIGIN', $_SERVER)) { | |
$origin = $_SERVER['HTTP_ORIGIN']; | |
} else if (array_key_exists('HTTP_REFERER', $_SERVER)) { | |
$origin = $_SERVER['HTTP_REFERER']; | |
} else { | |
$origin = $_SERVER['REMOTE_ADDR']; | |
} | |
// check if it matches | |
if (in_array($allowed_domains, $origin)) { | |
header('Access-Control-Allow-Origin: ' . $origin); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment