Reputation: 28249
I am looking for the best way to pipe data from one stream to another without having to deal with buffering myself. Basically the equivalent of the node.js stream.pipe function.
There is stream_copy_to_stream, but according to the comments on the manual page it is quite a memory hog (possibly reading the whole stream into memory?).
Of course I could do something like this:
$fh = fopen('filename.txt', 'rb');
$out = STDOUT;
while (!feof($fh)) {
$bytes = 1024;
fwrite(STDOUT, fread($fh, $bytes), $bytes);
}
fclose($fh);
But I'm hoping there is an easier API to accomplish this, without having to do the buffering myself.
Thanks.
Upvotes: 2
Views: 1310
Reputation: 6015
I downloaded the source code of PHP 5.4.0 and looked up stream_copy_to_stream (streams.c line 1419). It looks reasonable in my opinion.
First it tries to memory-map the source stream, and write the whole thing to the destination in one go without using an intermediate buffer.
If memory mapping is not possible, then it uses an internal buffer (8192 bytes, see CHUNK_SIZE in php_streams_int.h line 49) to shuffle the data from the source to the destination.
Either the manual comment is wrong, or the developers have improved the function since it was first written. I would give it another look.
Upvotes: 4