PHP Tutorial - PHP fgets() Function


fgets() is good for reading large files line by line. It sends back the next line as its return value.


string fgets ( resource $handle [, int $length ] )


  • handle - The file pointer opened by fopen() or fsockopen().
  • length - Reading ends when length - 1 bytes have been read, or a newline, or an EOF. If no length is specified, it will keep reading from the stream until it reaches the end of the line.


Returns a string of up to length - 1 bytes read from the file pointed to by handle. If there is no more data to read in the file pointer, then FALSE is returned.

If an error occurs, FALSE is returned.


Reads a large log line by line:

<?PHP/*w  ww  .  jav a 2  s  . c o m*/
     $access_log = fopen("access_log", "r");
     while (!feof($access_log)) {                                                                     
             $line = fgets($access_log);                                                              
             print $line;
             print "\n";