title: Cross-domain XMLHttpRequest, Access-Control-Allow-Origin header and $_SERVER['HTTP_ORIGIN']
body: <p>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.</p>
  
  <p>Searching on the net brought me to find out that I must allow these domains through headers like<br>
  <code>header("Access-Control-Allow-Origin: *");</code> or<br>
  <code>header("Access-Control-Allow-Origin: http://example.com");</code></p>
  
  <p>As I need more than one external domain, but still I find <code>*</code> much too open, further researches brought me on solutions relying on server-side comparison of <code>$_SERVER['HTTP_ORIGIN']</code> with authorized values. (on StackOverflow: <a href="https://stackoverflow.com/q/1653308/3872061">Access-Control-Allow-Origin Multiple Origin Domains?</a> for instance)</p>
  
  <p>BUT I found no mention of <code>$_SERVER['HTTP_ORIGIN']</code> in php manuel (<a href="http://php.net/manual/fr/reserved.variables.server.php" rel="nofollow noreferrer">http://php.net/manual/fr/reserved.variables.server.php</a>) and my tests revealed that this entry isn't always set.</p>
  
  <p><strong>So my questions are:<br>
  - when is the <code>$_SERVER['HTTP_ORIGIN']</code> superglobal set?<br>
  - is it reliable globally?... or client browser dependant?</strong></p>
  
  <p>It seems (but just empirically, from my tests / Firefox 34.0.5 &amp; ios Safari) that it is only set when 'needed', ie when request actually comes from another domain.  </p>
  
  <p>See short code extract hereunder to help understand the need<br>
  - no header sent if <code>$_SERVER['HTTP_ORIGIN']</code> not defined<br>
    (assuming it's effectively not a cross domain call, there shouldn't be any problem),<br>
  - send "allow" header if defined and belonging to an array of accepted domains.</p>
  
  <pre><code>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"); }
  }
  </code></pre>