Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP readfile vs. file_get_contents

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

like image 712
justnajm Avatar asked Nov 20 '13 11:11

justnajm


People also ask

Which is faster cURL or file_get_contents?

This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.

What is the difference between the file () and file_get_contents () functions?

file — Reads entire file contents into an array of lines. file_get_contents — Reads entire file contents into a string.

What is file_get_contents PHP?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.


1 Answers

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.

like image 173
Jesper Blaase Avatar answered Oct 05 '22 23:10

Jesper Blaase