Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

fgets

Reads one line from an open file.

Syntax

fgets(resource $stream, ?int $length = null): string|false

Parameters

ParameterTypeDescription
$streamresourceA file opened with `fopen()`.
$length?intOptional. The maximum number of bytes.

Return value

string|falseThe line including the line break, or `false` at the end of the file.

Examples

Reading line by line:

<?php
 
$file = sys_get_temp_dir() . '/ref-fgets.txt';
file_put_contents($file, "first\nsecond\nthird\n");
 
$handle = fopen($file, 'r');
 
while (($line = fgets($handle)) !== false) {
    echo strlen(rtrim($line)), ' ', rtrim($line), "\n";
}
 
fclose($handle);

Output:

5 first
6 second
5 third

Notes

This is how large files are read: only one line is in memory at a time. Remove the trailing line break with rtrim().

See also

  • fopen — Opens a file for reading or writing piece by piece.
  • feof — Checks whether the end of a file has been reached.
  • file — Reads a file into an array of lines.

Related recipes

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.