PHP | fgets( ) Function (original) (raw)

Last Updated : 11 May, 2018

The fgets() function in PHP is an inbuilt function which is used to return a line from an open file.

Syntax:

fgets(file, length)

Parameters Used: The fgets() function in PHP accepts two parameters. file : It specifies the file from which characters have to be extracted. length : It specifies the number of bytes to be read by the fgets() function. The default value is 1024 bytes.

Return Value : It returns a string of length -1 bytes from the file pointed by the user or False on failure.

Errors And Exceptions

  1. The function is not optimised for large files since it reads a single line at a time and it may take a lot of time to completely read a long file.
  2. The buffer must be cleared if the fgets() function is used multiple times.
  3. The fgets() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.

Suppose there is a file named “gfg.txt” which consists of :

This is the first line.
This is the second line.
This is the third line.

Program 1

<?php

$my_file = fopen ( "gfg.txt" , "rw" );

echo fgets ( $my_file );

fclose( $my_file );

?>

Output:

This is the first line.

Program 2

<?php

$my_file = fopen ( "gfg.txt" , "rw" );

while (! feof ( $my_file ))

`` {

`` echo fgets ( $my_file );

`` }

fclose( $my_file );

?>

Output:

This is the first line. This is the second line. This is the third line.

Reference:
http://php.net/manual/en/function.fgets.php