目录
本次讲述一下,在php文件下载的流程,及涉及到大文件时的问题
1.下载流程,可用2种函数处理
2.file_get_contents的实现机制和大文件的分段获取
过程总结
1.设置内存限制值
set_time_limit(0);
ini_set('memory_limit', '20480M');
2.获取文件名及路径(包括后缀如.txt)
3.文件内容获取(以下两种方式均可)
fopen($filePath,'rb');
fread($a,4096);
file_get_contents($filePath);
4.浏览器限制声明
http://www.360doc.com/content/19/0516/16/63398148_836125639.shtml
注:下图引用自上文
header("Content-Type: application/vnd.ms-excel;charset=gbk");
header("Content-Disposition: attachment; filename=你好呀.txt");
$ex = iconv('utf-8','gbk//TRANSLIT',$fp);//$fp为字符串
print(trim($ex));exit;
5.内容输出
文件读取函数
1.区别
file_get_contents() 把文件读入一个字符串
fopen() 将 filename 指定的名字资源绑定到一个流上
大文件用file_get_contents(),小文件用fopen()、fread()
$str = $content=file_get_contents("2.sql",FALSE,NULL,1024*1024,1024);
echo $str;
$fp=fopen('2.sql','r');
while (!feof($fp)){
$str.=fread($fp, filesize ($filename)/10);//每次读出文件10分之1
//进行处理
}
echo $str;
file_get_contents()
1.读大文件问题
发生内存溢出而打开错误
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。file_get_contents()将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败, file_get_contents() 将返回 FALSE。
file_get_contents()只能读取长度为 maxlen 的内容
2.如何读大文件
分段:
$a =file_get_contents( $u,100,1000 );
$str = $content=file_get_contents("2.sql",FALSE,NULL,1024*1024,1024);
echo $str;
file_get_contents如果正常返回,会把文件内容储存到某个字符串中,所以它不应该返回超过2G长度的字符串。
如果文件内容超过2G,不加offset和maxlen调用file_get_contents的话,肯定会返回false,
3.fread()函数如何分段读取?
没结束就一直读
$fp=fopen('2.sql','r');
while (!feof($fp)){
$str.=fread($fp, filesize ($filename)/10);//每次读出文件10分之1
//进行处理
}
echo $str;
4.如何设置file_get_contents函数的超时时间?
注:代码来自该链接
https://www.cnblogs.com/Renyi-Fan/p/9642301.html
<?php
//设置超时参数
$opts=array(
"http"=>array(
"method"=>"GET",
"timeout"=>3
),
);
创建数据流上下文
$context = stream_context_create($opts);
//$url请求的地址,例如:
$result =file_get_contents($url, false, $context);
// 打印结果
print_r($result);
?>