PHP 8.4.0 RC3 available for testing

stream_get_line

(PHP 5, PHP 7, PHP 8)

stream_get_lineObtém uma linha do recurso do fluxo até um delimitador informado

Descrição

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

Obtém uma linha do manipulador informado.

A leitura termina quando o número de bytes especificados em length tiverem sido lidos, ou quando a string não vazia especificada por ending for encontrada (que não é incluída no valor de retorno), ou em EOF (o que ocorrer primeiro).

Esta função é praticamente idêntica a fgets() exceto por permitir delimitadores de final de linha diferente dos padrões \n, \r e \r\n, e não retorna o delimitador em si.

Parâmetros

stream

Um manipulador de arquivo válido.

length

O número máximo de bytes para leitura do manuipulador. Valores negativos não são suportados. Zero (0) define o tamanho padrão do pacote do socket, isto é, 8192 bytes.

ending

Um delimitador string opcional.

Valor Retornado

Retorna uma string com no máximo o número de bytes de length lidos do arquivo apontado por stream, ou false em caso de falha.

Veja Também

  • fread() - Leitura de arquivo segura para binário
  • fgets() - Lê uma linha de um ponteiro de arquivo
  • fgetc() - Lê um caractere do ponteiro de arquivo
adicione uma nota

Notas Enviadas por Usuários (em inglês) 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