title: PHP Access-Control-Allow-Origin header not working
body: <p>I'm working on a JavaScript script that makes AJAX requests to another server (my own domain). The JavaScript script is added to the page using a plugin. It should retrieve data from a PHP file on my domain. </p>
  
  <p>I've added the following header to the PHP file:</p>
  
  <pre><code>&lt;?php
  header("Access-Control-Allow-Origin: *");
  </code></pre>
  
  <p>but the AJAX request still throws an error. Changing the * to the actual domain I plan to use it on doesn't work either. I've searched stack overflow for answers, and came across the following:</p>
  
  <pre><code>// Allow from any origin
  if (isset($_SERVER['HTTP_ORIGIN'])) {
      header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
      header('Access-Control-Allow-Credentials: true');
      header('Access-Control-Max-Age: 86400');    // cache for 1 day
  }
  
  // Access-Control headers are received during OPTIONS requests
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  
      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
          header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
  
      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
          header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
  
      exit(0);
  }
  </code></pre>
  
  <p>which doesn't work, either.</p>
  
  <p>I thought my .htaccess file may have somehow affected things, so I deleted it temporarily, but the AJAX request still said no Access-Control-Allow-Origin header was set in the PHP file.</p>
  
  <p>I've found this on daniweb.com:
  <a href="https://www.daniweb.com/web-development/php/threads/461902/php-header-is-not-working-for-access-control-allow-origin" rel="nofollow">https://www.daniweb.com/web-development/php/threads/461902/php-header-is-not-working-for-access-control-allow-origin</a>
  which was unresolved. </p>
  
  <p>If the headers have definitely been set (in multiple ways), how come the AJAX request still throws an error, stating the headers haven't been set? </p>