php 文件跑服务,使用PHP服务文件的最快方式

我试图把一个函数接收一个文件路径,标识它是什么,设置相应的头,并像Apache一样服务。

我这样做的原因是因为我需要使用PHP处理一些关于请求的信息,然后提供文件。

速度至关重要

virtual()不是一个选项

必须在共享托管环境中工作,用户无法控制Web服务器(Apache / nginx等)

这里是我到目前为止:

File::output($path);

class File {

static function output($path) {

// Check if the file exists

if(!File::exists($path)) {

header('HTTP/1.0 404 Not Found');

exit();

}

// Set the content-type header

header('Content-Type: '.File::mimeType($path));

// Handle caching

$fileModificationTime = gmdate('D, d M Y H:i:s', File::modificationTime($path)).' GMT';

$headers = getallheaders();

if(isset($headers['If-Modified-Since']) && $headers['If-Modified-Since'] == $fileModificationTime) {

header('HTTP/1.1 304 Not Modified');

exit();

}

header('Last-Modified: '.$fileModificationTime);

// Read the file

readfile($path);

exit();

}

static function mimeType($path) {

preg_match("|\.([a-z0-9]{2,4})$|i", $path, $fileSuffix);

switch(strtolower($fileSuffix[1])) {

case 'js' :

return 'application/x-javascript';

case 'json' :

return 'application/json';

case 'jpg' :

case 'jpeg' :

case 'jpe' :

return 'image/jpg';

case 'png' :

case 'gif' :

case 'bmp' :

case 'tiff' :

return 'image/'.strtolower($fileSuffix[1]);

case 'css' :

return 'text/css';

case 'xml' :

return 'application/xml';

case 'doc' :

case 'docx' :

return 'application/msword';

case 'xls' :

case 'xlt' :

case 'xlm' :

case 'xld' :

case 'xla' :

case 'xlc' :

case 'xlw' :

case 'xll' :

return 'application/vnd.ms-excel';

case 'ppt' :

case 'pps' :

return 'application/vnd.ms-powerpoint';

case 'rtf' :

return 'application/rtf';

case 'pdf' :

return 'application/pdf';

case 'html' :

case 'htm' :

case 'php' :

return 'text/html';

case 'txt' :

return 'text/plain';

case 'mpeg' :

case 'mpg' :

case 'mpe' :

return 'video/mpeg';

case 'mp3' :

return 'audio/mpeg3';

case 'wav' :

return 'audio/wav';

case 'aiff' :

case 'aif' :

return 'audio/aiff';

case 'avi' :

return 'video/msvideo';

case 'wmv' :

return 'video/x-ms-wmv';

case 'mov' :

return 'video/quicktime';

case 'zip' :

return 'application/zip';

case 'tar' :

return 'application/x-tar';

case 'swf' :

return 'application/x-shockwave-flash';

default :

if(function_exists('mime_content_type')) {

$fileSuffix = mime_content_type($path);

}

return 'unknown/' . trim($fileSuffix[0], '.');

}

}

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值