[英]PHP fread not working after successful fopen, write and fclose
这是一大早,我只是没有得到这个:
以下代码有效,文件放在服务器上:
$filename = $ioid . "_" . time();
$fp = fopen("$filename.csv", "w+");
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
但这不能直接使用(文件是105k):
$fp2 = fopen("$filename.csv", "r");
$output = fread($fp2, 1000000000000);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $output;
fclose($fp2);
没有读取任何内容,也没有任何内容打印到页面上。
我做错了什么显而易见的事情? :)
你的问题是fread($fp2, 1000000000000)
试图分配1TB的大缓冲区来读取文件并明显达到允许的内存限制,除非你是在32位平台上发生整数溢出 。 无论哪种方式,它都无法正常工作。
如果要将整个文件读取到输出缓冲区并快速执行,请使用readfile()
如下所示:
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename.csv");
readfile("$filename.csv")
务必下次检查错误日志。
此外,如果您不打算将结果文件存储在磁盘上,我建议您重新制作脚本以使用更安全的方法:
$fp = tmpfile(); // creates a handle for a temporary file with a unique name
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
rewind($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=report.csv");
fpassthru($fp);
fclose($fp); // this removes the file
这个问题在于fread
论证。 你的代码产生:
Warning: fread() [function.fread]: Length parameter must be greater than 0
例如,当将1000000000000更改为1000时,它可以正常工作。 所以:用这种方式:
$output = file_get_contents("filename.csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $output;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.