title: Optimize PHP for Serving All Files (And Not Apache)
body: <p>I have a need to send all requests for any web resource through PHP for user authentication purposes, and to not serve any files directly through Apache. Here's my .htaccess:</p>
  
  <pre><code># All requests are routed to PHP (images, css, js, everything)
  RewriteRule ^(.*)$ index.php?query=$1&amp;%{QUERY_STRING} [L]
  </code></pre>
  
  <p>I then process the request, verify the user has access to the resource, and then output any file that does not require processing using the following PHP read function. It turns out that this is incredibly slow compared to just letting Apache do its thing.</p>
  
  <p>Can anyone recommend a way to help me improve performance?</p>
  
  <pre><code>static function read($path) {
      if(!File::exists($path)) {
          //echo 'File does not exist.';
          header("HTTP/1.0 404 Not Found");
          return;
      }
  
      $fileName = String::explode('/', $path);
      if(Arr::size($fileName) &gt; 0) {
          $fileName = $fileName[Arr::size($fileName) - 1];
      }
  
      $size = File::size($path);
      $time = date('r', filemtime($path));
  
      $fm = @fopen($path, 'rb');
      if(!$fm) {
          header("HTTP/1.0 505 Internal server error");
          return;
      }
  
      $begin = 0;
      $end = $size;
  
      if(isset($_SERVER['HTTP_RANGE'])) {
          if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
              $begin = intval($matches[0]);
              if(!empty($matches[1]))
                  $end = intval($matches[1]);
          }
      }
  
      if ($begin &gt; 0 || $end &lt; $size)
          header('HTTP/1.0 206 Partial Content');
      else
          header('HTTP/1.0 200 OK');
  
      // Find the mime type of the file
      $mimeType = 'application/octet-stream';
      //$finfo = @new finfo(FILEINFO_MIME);
      //print_r($finfo);
      //$fres = @$finfo-&gt;file($path);
      //if(is_string($fres) &amp;&amp; !empty($fres)) {
         //$mimeType = $fres;
      //}
  
      // Handle CSS files
      if(String::endsWith('.css', $path)) {
          $mimeType = 'text/css';
      }
  
      header('Content-Type: '.$mimeType);
      //header('Cache-Control: public, must-revalidate, max-age=0');
      //header('Pragma: no-cache');
      header('Accept-Ranges: bytes');
      header('Content-Length:' . ($end - $begin));
      header("Content-Range: bytes $begin-$end/$size");
      header("Content-Disposition: inline; filename=$fileName");
      header("Content-Transfer-Encoding: binary\n");
      header("Last-Modified: $time");
      header('Connection: close');
  
      $cur = $begin;
      fseek($fm, $begin, 0);
  
      while(!feof($fm) &amp;&amp; $cur &lt; $end &amp;&amp; (connection_status() == 0)) {
          print fread($fm, min(1024 * 16, $end - $cur));
          $cur += 1024 * 16;
      }
  }
  </code></pre>