What is fgets in PHP?

PHP offers many functions for file manipulation. The fgets function in PHP reads a line from an already open file.

Syntax

The syntax for the fgets function is shown below:

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

Parameters

The fgets function has two parameters:

  • file: This is a required parameter. file is the name of the file stream that points to an already open file. A line will be returned from this file.
  • length: This is an optional parameter. The length parameter specifies the number of bytes to be read from the file.

Return value

The fgets() function returns a single line, read from the file.

If the function is unable to return a line due to an error or by coming to the end of the file, it returns false.

Working of fgets function.

Code

The following code shows how we can use the fgets function.

main.php
test.txt
<?php
$file = fopen("test.txt","r"); // open the file
//example without length
while(!feof($file)) //checks if at end of the file
{
echo fgets($file); //reads one line from the file
}
// example with length
while(!feof($file)) //checks if at end of the file
{
echo fgets($file, 12); //reads 12 bytes line from the file
}
fclose($file); // close the file
?>
Copyright ©2024 Educative, Inc. All rights reserved