PHP Fgets () Function

PHP

PHP fgets() function - it is a built-in function that is used to return a line from an open file.
  • It is used to return a line from a file pointer and stops returning at the specified length, at the end of the file (EOF) or on a new line, at whichever comes first.
  • The file to read and the number of bytes to read are sent as parameters to fgets(), and it returns a -1 byte string from the file specified by the user.
  • Returns False on failure.
  • 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. 
Returned value:Returns a -1 byte string from a file specified by the user, or False on error.Errors and Exceptions
  • This function is not optimized for large files as it reads one line at a time and a long file can take a long time to fully read.
  • The buffer must be cleared if fgets() is used multiple times.
  • The fgets() function returns Boolean False, but it often happens that it returns a non-boolean value that 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
      // the file is opened using the fopen() function $my_file = fopen ( "gfg.txt" , "rw" );  
    // Prints one line from the open file pointer echo fgets ( $my_file );  
    // file is closed with fclose() fclose ( $my_file ); ?>
    Output:
    This is the first line. 
    Program 2
    // the file is opened using the fopen() function $my_file = fopen ( "gfg.txt " , " rw " );  
    // prints one line at a time until the end of the file is reached while (! feof ( $my_file )) { echo fgets ( $my_file ); }  
    // the file is closed using the fclose() function fclose ( $my_file ); ?>
    Output:
    This is the first line. This is the second line. This is the third line. 
    Link:
    http://php.net/ manual / en / function.fgets.php