stream_get_line

(PHP 5, PHP 7, PHP 8)

stream_get_lineGets line from stream resource up to a given delimiter

Description

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

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.

Parameters

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.

Return Values

Returns a string of up to length bytes read from the file pointed to by stream, or false on failure.

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetc() - Gets character from file pointer
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