(PHP 5, PHP 7, PHP 8)
stream_get_line — Gets line from stream resource up to a given delimiter
Gets a line from the given handle.
Reading ends when length
bytes have been read, when
the non-empty string specified by ending
is found (which is
not included in the return value), or on EOF
(whichever comes first).
This function is nearly identical to fgets() except in that it allows end of line delimiters other than the standard \n, \r, and \r\n, and does not return the delimiter itself.
stream
A valid file handle.
length
The maximum number of bytes to read from the handle.
Negative values are not supported.
Zero (0
) means the default socket chunk size,
i.e. 8192
bytes.
ending
An optional string delimiter.
Returns a string of up to length
bytes read from the file
pointed to by stream
, or false
on failure.
fgets is faster but stream_get_line is more useful in a tcp server scripts.
when fgets reads some bytes from socket, where EOF is reached, it returns bool(false) same as stream_get_line
BUT if remote client drops connection, and server script will try to read some data with function fgets, function will return bool(false), and stream_get_line will return string(0) ""
so you can detect remote client disconnection with stream_get_line, and cannot with fgets
This function is very efficient to redirect streams. I have older scripts to compare, and recent versions of PHP are so fast, that sometimes 2 lines might get fed into one, and this happens only on PHP 8.3 and 8.4.
After digging, i found that throttling a bit is the best to do to maintain retro compatibility.
$line = stream_get_line($response, 1024, "\n");
usleep(10000);