Skip to content

Instantly share code, notes, and snippets.

@Yalme
Created November 17, 2023 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yalme/120981d3e66bf107cf49cb37512e0eea to your computer and use it in GitHub Desktop.
Save Yalme/120981d3e66bf107cf49cb37512e0eea to your computer and use it in GitHub Desktop.
PHP CORS Access Control Cross-Origin Header
<?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