Stream behavior in PHP
17:18 24 Jul 2026

When getting a stream from an API using cURL with CURLOPT_WRITEFUNCTION I can keep a stream alive. A callback function can do things with the data as it comes in.

But I can't do this with fopen() and fgets() because the stream closes when it reaches a '' or EOF.

What I would like to do is constantly be checking a file that gets appended unpredictably. Something like:

$handle = fopen('file:///home/me/myfile', 'r');
while(1){
 $line = fgets($handle);
 echo $line;
}

...with the desired behavior of the while looping through the existing lines of /home/me/myfile and then when its out of lines, continue looping but NOT close the stream at EOF. That way if myfile gets appended with a new line, the stream will pick it up. As it is now, the loop will continue, but the stream is closed and $line will not be set as the newly appended line.

I understand that the stream is primarily used for reading large files, not files being continuously updated, but then how is it done in CURLOPT_WRITEFUNCTION? Is there a way to use curl locally to get a similar result?

I've seen these questions sort of on this topic already:

How to keep input stream open after piping to PHP process?

How do I flush STDIN in a PHP console application?

advice php stream