PHP readfile vs. file_get_contents

justnajm picture justnajm · Nov 20, 2013 · Viewed 33.6k times · Source

I have used following code to generate 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

Answer

Jesper Blaase picture Jesper Blaase · Nov 20, 2013

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.