为了账号安全,请及时绑定邮箱和手机立即绑定

使用PHP服务文件的最快方法

使用PHP服务文件的最快方法

MM们 2019-12-07 16:39:03
我试图将一个函数接收一个文件路径,确定它是什么,设置适当的标头,并像Apache一样提供服务。我这样做的原因是因为在提供文件之前,我需要使用PHP处理有关请求的某些信息。速度至关重要virtual()不是一个选择必须在用户无法控制Web服务器(Apache / nginx等)的共享托管环境中工作到目前为止,这是我得到的:File::output($path);<?phpclass 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';?>
查看完整描述

3 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

最快的方法:不要。查看nginx的x-sendfile标头,其他Web服务器也有类似的内容。这意味着您仍然可以在php中进行访问控制等,但是将文件的实际发送委托给为此设计的Web服务器。


PS:我觉得不寒而栗,只是想与在php中读取和发送文件相比,将它与nginx结合使用会更有效率。试想一下,如果有100个人正在下载文件:使用php + apache,那么慷慨,那大概是100 * 15mb = 1.5GB(大约,给我射击),就在那儿。Nginx只会将文件发送到内核,然后将其直接从磁盘加载到网络缓冲区中。迅速!


PPS:而且,使用这种方法,您仍然可以执行所有访问控制和所需的数据库工作。


查看完整回答
反对 回复 2019-12-07
  • 3 回答
  • 0 关注
  • 675 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信