Home  >  Article  >  php教程  >  基于php下载文件的详解

基于php下载文件的详解

WBOY
WBOYOriginal
2016-06-13 11:52:28865browse

php下载文件,比如txt文件。
出现的效果就是,弹出浏览器自带的下载框,出现另存为操作。有时候会出现内存溢出和超时的现象。
超时的话,设置set_time_limit(0);
出现内存溢出的话,有可能是因为从数据库中取出的数据量太大导致的。
如果是从文件中读取的话,出现内存溢出的话,就是代码读取方式不正确,调用files或者filegetcontens才会
如果是fopen的话,就给一个缓冲区,固定大小,读入然后写入,不会出现内存溢出的情况。
如代码:

复制代码 代码如下:


if (file_exists($file_path)) { //如果文件存在
$handle = fopen($file_path, "r");
while (!feof($handle)) {
$content = fgets($handle, 4096); //读取一行
echo $content; //输出到缓冲区,即php://stdout。达到缓冲区设置值后由tcp传给浏览器进行输出  一般到512字节就会通过网络输出给浏览器
}
fclose($handle);
}


但是在输出之前,要调用一次,@ob_end_flush();不能循环调用,只调用一次就好。
@ob_end_flush();//冲刷出(送出)输出缓冲区内容并关闭缓冲

文件下载:
content-type://下载的格式,浏览器不能解析的格式就会弹出下载框

复制代码 代码如下:


header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Transfer-Encoding: binary");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
Header("Content-type: application/octet-stream");  //响应内容类型  
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($filename). ' bytes');
Header('Content-Disposition: attachment; filename='.$filename);  //HTTP响应头


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn