PHP 读取文件与 file_get_contents

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20095175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:52:07  来源:igfitidea点击:

PHP readfile vs. file_get_contents

phpfunctionfilesystemsreadfile

提问by justnajm

I have used following code to generate zip

我使用以下代码生成zip

// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);

this code works fine but for unknown reasons was not working until I tried

此代码工作正常,但由于未知原因在我尝试之前无法正常工作

// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
echo file_get_contents($zip_name);

I am curious about finding what is happening in both the cases

我很好奇在这两种情况下都发生了什么

回答by Jesper Blaase

Readfile will read the file directly into the output buffer, and file_get_contents will load the file into memory, when you echo the result the data is copied from memory to the output buffer effectively using 2 times the memory of readfile.

Readfile 会将文件直接读入输出缓冲区,file_get_contents 会将文件加载到内存中,当您回显结果时,数据将从内存复制到输出缓冲区,有效地使用了 readfile 的 2 倍内存。