PHPのお勉強!

PHP TOP

stream_get_line

(PHP 5, PHP 7, PHP 8)

stream_get_line指定されたデリミタの位置までのデータを一行分としてストリームから読み込む

説明

stream_get_line(resource $stream, int $length, string $ending = ""): string|false

指定したハンドルから一行取得します。

読み込みは、length バイト読まれたか、 ending で指定された空でない文字列がストリームに見つかったか (この文字列は返値に 含まれません)、あるいは EOF に達したとき、のうち一番最初に遭遇したところで停止します。

この関数は fgets() とほとんど同一ですが、 \n や \r 、\r\n といった一般的な文字列以外を行末を示すデリミタ として指定できる点で、またデリミタ自体を返値に 含まない 点で異なります。

パラメータ

stream

有効なファイルハンドル。

length

ハンドルから読み込む最大バイト数。 負の値はサポートされていません。 ゼロ(0) を指定すると、 ソケットのデフォルトのチャンクサイズ つまり、8192 を使います。

ending

オプションのデリミタ文字列。

戻り値

最大 length バイトの、 stream で指定されたファイルから読み込んだデータを返します。 失敗した場合に false を返します

参考

  • fread() - バイナリセーフなファイルの読み込み
  • fgets() - ファイルポインタから 1 行取得する
  • fgetc() - ファイルポインタから1文字取り出す
add a note

User Contributed Notes 2 notes

up
12
pk at ritm dot ru
14 years ago
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
up
9
Anonymous
12 years ago
WARNING:
Specifying a length of 0 does NOT give you an infinite length, contrary to what the documentation might suggest. Instead, setting a length of 0 just makes the function default to a length of 8192. To be precise, it gets the value PHP_SOCK_CHUNK_SIZE (8192) in ext/standard/streamsfuncs.c.

So, let's say you're trying to read ALL data until you reach a "\x03" (decimal 3) byte. How do you GUARANTEE that this is the case? Well, there's no way! The only thing you can do stream_get_lin() into a "master" string, then fseek() backwards by 1 character, then fgetc() and verify that it's "\x03". If you don't see a "\x03", it means that stream_get_line() has aborted after 8192 bytes and before hitting "\x03", and you'll have to call it again. Keep appending the return values to a "master" string until you hit a "\x03" or EOF... That's the ONLY way to properly build a string that contains EVERYTHING until the character you're looking for.
To Top