(PHP 5, PHP 7, PHP 8)
stream_get_line — 指定されたデリミタの位置までのデータを一行分としてストリームから読み込む
指定したハンドルから一行取得します。
読み込みは、length
バイト読まれたか、
ending
で指定された空でない文字列がストリームに見つかったか
(この文字列は返値に 含まれません)、あるいは
EOF に達したとき、のうち一番最初に遭遇したところで停止します。
この関数は fgets() とほとんど同一ですが、 \n や \r 、\r\n といった一般的な文字列以外を行末を示すデリミタ として指定できる点で、またデリミタ自体を返値に 含まない 点で異なります。
stream
有効なファイルハンドル。
length
ハンドルから読み込む最大バイト数。
負の値はサポートされていません。
ゼロ(0
) を指定すると、
ソケットのデフォルトのチャンクサイズ
つまり、8192
を使います。
ending
オプションのデリミタ文字列。
最大 length
バイトの、
stream
で指定されたファイルから読み込んだデータを返します。
失敗した場合に false
を返します
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);