title: PHP Content Length Mismatch with custom content delivery script
body: <p>Good day everyone,</p>
  
  <p>When developing a hobby website I encountered the following problem. To prevent unauthorized users from accessing image files on the server I set the folder containing the images to deny-all in nginx. This works fine but when I use the following PHP script to access the image files in the folder, Chrome randomly refuses to load them giving the following error: 'net::ERR_CONTENT_LENGTH_MISMATCH'. With random I mean that sometimes the images will load fine. I have tried to flush the output buffer before and after the readfile() call but nothing seems to solve the problem. Thanks in advance for helping me out!</p>
  
  <p>PS: If you would like to see more source code/configuration files just let me know.</p>
  
  <p>The PHP script:</p>
  
  <pre><code>&lt;?php
  if(!empty($_GET['tconst'])) {
  
          //Included login script contains this method
          if(login_check($mysqlisecure)) {
              $tconst = preg_replace( '#[^.\w]#', '', $_GET['tconst'] );
  
              $file = "{$_SERVER['DOCUMENT_ROOT']}/content/posters/{$tconst}.jpg";
  
              if (file_exists($file)) {
  
                  $filesize = filesize($file);
  
                  header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60 * 24)));
                  header("Content-Type: image/jpeg");
                  header("Content-Length: ".$filesize);
  
                  readfile($file);
              }
          }
  }
  exit();
  </code></pre>