apache mod_xsendfile提高php文件下载速度的方法

说明:
apache服务器中提供一个文件下载,一般使用一个url指向服务器中的文件即可提供下载。
缺点:不能进行统计,权限检测等操作。

1,一般使用php提供下载,例如:
 

复制代码代码示例:
<?php  
$file = 'test.zip';  
if(file_exists($file)){  
    header('content-type:application/octet-stream');  
    header('content-disposition:attachment; filename='.basename($file));  
    header('content-length:'.filesize($file));  
    readfile($file);  
}  
?> 

2,处理中文文件名:
 

复制代码代码示例:
<?php  
$file = 'test.zip';  
$filename = '中文.zip';  
  
if(file_exists($file)){  
    $user_agent = $_SERVER['Http_User_agent'];  
    $encode_filename = rawurlencode($filename);  
  
    if(preg_match("/MSIE/", $user_agent)){  
        header('content-disposition:attachment; filename="'.$encode_filename.'"');  
    }else if(preg_match("/Firefox/", $user_agent)){  
        header("content-disposition:attachment; filename*=\"utf8''".$filename.'"');  
    }else{  
        header('content-disposition:attachment; filename="'.$filename.'"');  
    }  
    readfile($file);  
}  
?>  
 

使用php readfile,需要经过php这层。

如果可以直接通过apache将文件发送给用户,不经过php这层,将会提高下载速度。
那么就需要用到本文的主角了,它就是apache mod_xsendfile模块,下载地址:mod_xsendfile(https://tn123.org/mod_xsendfile/),让apache直接将文件发给用户

1,安装mod_xsendfile模块:
 

复制代码代码示例:
sudo apxs2 -cia mod_xsendfile.c  
sudo a2enmod xsendfile  
sudo /etc/init.d/apache2 restart  
 

apxs2 用于编译apache module,需要安装apache2-dev

2,设置xsendfile打开:
 

复制代码代码示例:
<Directory>  
XSendFile On  
</Directory> 

3,mod_xsendfile模块的实例代码。
 

复制代码代码示例:
<?php
/**
* mod_xsendfile模块 加速文件下载
* edit: www.jbxue.com
*/
$file = 'test.zip';  
$filename = '中文.zip';  
  
if(file_exists($file)){  
    $user_agent = $_SERVER['Http_User_agent'];  
    $encode_filename = rawurlencode($filename);  
  
    if(preg_match("/MSIE/", $user_agent)){  
        header('content-disposition:attachment; filename="'.$encode_filename.'"');  
    }else if(preg_match("/Firefox/", $user_agent)){  
        header("content-disposition:attachment; filename*=\"utf8''".$filename.'"');  
    }else{  
        header('content-disposition:attachment; filename="'.$filename.'"');  
    }  
    header('X-Sendfile:'.$file);  
}  
?> 
 
posted @ 2015-05-18 15:56  教育软件工作室  阅读(237)  评论(0编辑  收藏  举报