Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is stream_get_contents lower level and faster than file_get_contents?

From a comment to this answer I read that "stream_get_contents is low-level" comparing to file_get_contents. However according to Manual, stream_get_contents is

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

Which statement is correct? Is stream_get_contents really lower level and faster?

Specifically I am interested in reading local files from HD.

like image 246
Dmitri Zaitsev Avatar asked Dec 19 '13 05:12

Dmitri Zaitsev


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 Stream_get_contents?

stream_get_contents — Reads remainder of a stream into a string.

What is the function file_get_contents () useful for?

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.

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

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


1 Answers

I'm late here but it might help others

file_get_contents() loads the file content into memory. It sits there in memory and waits for the program to call echo upon which it will be delivered to the output buffer.

A good usage example is:

echo file_get_contents('file.txt');

stream_get_contents() delivers the content on an already open stream. An example is this:

$handle = fopen('file.txt', 'w+');
echo stream_get_contents($handle);

You could see that stream_get_contents() used an existing stream created by fopen() to get the contents as a string.

file_get_contents() is the more preferred way as it doesn't depend on an open stream, and is efficient with your memory using memory mapping techniques. For external sites reading, you can also set HTTP headers when getting the content. (Refer to https://www.php.net/manual/en/function.file-get-contents.php for more info)

For larger files/resources, stream_get_contents() may be preferred as it delivers the content fractionally as opposed to file_get_contents() where the entire data is dumped in memory.

like image 148
Joshua Etim Avatar answered Oct 14 '22 01:10

Joshua Etim