PHP readfile与file_get_contents

jus*_*ajm 31 php filesystems function readfile

我使用以下代码生成zip

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

这段代码工作正常,但由于不明原因,直到我尝试才行

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

我很好奇在两种情况下都能找到正在发生的事情

Jes*_*ase 54

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

  • 是的,这就是我的观察结果,readfile 在生成文件时试图抛出文件,但 file_get_contents 会等到它成功生成。 (3认同)