Is stream_get_contents lower level and faster than file_get_contents?
Asked Answered
D

1

7

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.

Dupont answered 19/12, 2013 at 5:44 Comment(0)
B
3

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.

Brainsick answered 18/1, 2021 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.