欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于php下载文件的详解

程序员文章站 2022-04-28 10:15:15
php下载文件,比如txt文件。出现的效果就是,弹出浏览器自带的下载框,出现另存为操作。有时候会出现内存溢出和超时的现象。超时的话,设置set_time_limit(0);...
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响应头