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:
# All requests are routed to PHP (images, css, js, everything)
RewriteRule ^(.*)$ index.php?query=$1&%{QUERY_STRING} [L]
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.
Can anyone recommend a way to help me improve performance?
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) > 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 > 0 || $end < $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->file($path);
//if(is_string($fres) && !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) && $cur < $end && (connection_status() == 0)) {
print fread($fm, min(1024 * 16, $end - $cur));
$cur += 1024 * 16;
}
}