title: PHP: Streaming Images Outside of Webroot and Caching
body: <p>I'm using Apache and when I request an image directly for the first time, the status of the image is "200 OK". Subsequent requests have a status of "304 Not Modified", which is good because it saves bandwidth for both the client and server.</p>
  
  <p>I'm working on a website that will allow users to upload images. These images need to be stored outside of the webroot not just to prevent hotlinking, but also so I can collect statistics on the images. So my thought was to use a PHP script like this to stream the images:</p>
  
  <pre><code>&lt;?php
  
      $image_to_stream = '/path/outside/of/webroot/image.jpg';
      $cache_seconds = 2592000; // 30 days
  
      header("Cache-Control: max-age=$cache_seconds");
      header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_seconds) . ' GMT');
      header('Pragma: cache');
      header('Content-Type: image/jpg');
      header('Content-length: ' . filesize($image_to_stream));
  
      readfile($image_to_stream);
  
  ?&gt;
  </code></pre>
  
  <p>However, the script appears to always have a status of "200 OK" and the entire image gets streamed. Is there a way to fix this or should I be taking another approach or what? Thanks!</p>