2

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"); }
}
fpierrat
  • 703
  • 5
  • 23
  • We're not here to review your code. We're here to help fix someones programming errors. – Daan Dec 15 '14 at 11:10
  • I'm not requiring code review. I simply can't find help in php's manual on a $_SERVER entry that's quoted in other SO questions/answers. I thought here was the place to ask other's help when encountering problems where documentation brought no help. Sorry if I'm thus mistaken... – fpierrat Dec 15 '14 at 11:19
  • edited to make clearer that the question is an information request on an (as far as i could see) undocumented php superglobal, and no code review request. – fpierrat Dec 16 '14 at 09:42

1 Answers1

1

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.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • Thanks, searching on CORS enabled me to find all information i needed in the w3 specs (http://www.w3.org/TR/cors/) – fpierrat Dec 16 '14 at 10:04