<?php
namespace ROF;
/**
* For delivering files based upon their mimetype. Requires "ralouphie/mimey": "2.1.*"
*
*/
class Mime {
static public function deliverFile($filePath){
$path = $filePath; //copy-pasted code. easier to just reassign the variable
if (!is_file($filePath)){
throw new \Exception("File '{$filePath}' does not exist. Error in \ROF\Mime::deliverFile(...)");
}
$extension = pathinfo($path,PATHINFO_EXTENSION);
$mimey = new \Mimey\MimeTypes;
$mime_type = $mimey->getMimeType($extension);
$headers = apache_request_headers();
$fn = $path;
// Checking if the client is validating his cache and if it is current.
$mtime = filemtime($fn);
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == $mtime) &&$mtime !==FALSE) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
//header('Content-Length: '.filesize($fn));
header('Content-type: '.$mime_type);
header('Cache-Control: max-age='.(60*60*24*30));
readfile($fn);
}
}
static public function setHeaders($filePath,$asExt=null){
$extension = $asExt ?? pathinfo($path,PATHINFO_EXTENSION);
$path = $filePath; //copy-pasted code. easier to just reassign the variable
$mimey = new \Mimey\MimeTypes;
$mime_type = $mimey->getMimeType($extension);
$headers = apache_request_headers();
$fn = $path;
// Checking if the client is validating his cache and if it is current.
$mtime = filemtime($fn);
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == $mtime) &&$mtime !==FALSE) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
//header('Content-Length: '.filesize($fn));
header('Content-type: '.$mime_type);
header('Cache-Control: max-age='.(60*60*24*30));
// readfile($fn);
}
}
static public function mimeFromExt($extension){
$mimey = new \Mimey\MimeTypes;
$mime_type = $mimey->getMimeType($extension);
return $mime_type;
}
static public function getHeaderForExt($extension){
$mime_type = static::mimeFromExt($extension);
return 'Content-Type: '.$mime_type;
}
}
?>