Reputation: 804
I need a script to deliver information to requesting-pages hosted on different domains, through XMLHttpRequest. There are many questions and answers on the subject, but none of the ones I found fully answered my questions.
Searching on the net brought me to find out that I must allow these domains through headers like
header("Access-Control-Allow-Origin: *");
or
header("Access-Control-Allow-Origin: http://example.com");
As I need more than one external domain, but still I find *
much too open, further researches brought me on solutions relying on server-side comparison of $_SERVER['HTTP_ORIGIN']
with authorized values. (on StackOverflow: Access-Control-Allow-Origin Multiple Origin Domains? for instance)
BUT I found no mention of $_SERVER['HTTP_ORIGIN']
in php manuel (http://php.net/manual/fr/reserved.variables.server.php) and my tests revealed that this entry isn't always set.
So my questions are:
- when is the $_SERVER['HTTP_ORIGIN']
superglobal set?
- is it reliable globally?... or client browser dependant?
It seems (but just empirically, from my tests / Firefox 34.0.5 & ios Safari) that it is only set when 'needed', ie when request actually comes from another domain.
See short code extract hereunder to help understand the need
- no header sent if $_SERVER['HTTP_ORIGIN']
not defined
(assuming it's effectively not a cross domain call, there shouldn't be any problem),
- send "allow" header if defined and belonging to an array of accepted domains.
if(isset($_SERVER['HTTP_ORIGIN'])) {// in case of cross domain ajax call
$http_origin = $_SERVER['HTTP_ORIGIN'];
if(in_array($http_origin, $ajaxAllowedDomains))
{ header("Access-Control-Allow-Origin: $http_origin"); }
}
Upvotes: 2
Views: 2494
Reputation: 944256
when is the
$_SERVER['HTTP_ORIGIN']
superglobal set?
When the HTTP request includes an Origin
header. Browsers will set one when making a cross-domain request with XMLHttpRequest.
is it reliable globally?
It is in situations where you might want to set CORS response headers.
Upvotes: 1