PHPRO.ORG

This seems such a simple task, and many coders leap to the first tool availabe, the file() function. This works fine for small files but if the file increases, the PHP memory limit is soon reached and an error is produced. This is because PHP has to read the file into an array and store it internally, not an efficient method. The method shown below prevents this but iterating over the file line by line. This allows us to handle files of any size without running out of memory.


<?php
 
/*** example usage ***/
 
echo countLines("/path/to/file.txt");

 
/**
 *
 * @Count lines in a file
 *
 * @param string filepath 
 *
 * @return int
 *
 */
 
function countLines($filepath
 {
    
/*** open the file for reading ***/
    
$handle fopen$filepath"r" );
    
/*** set a counter ***/
    
$count 0;
    
/*** loop over the file ***/
    
while( fgets($handle) ) 
    {
        
/*** increment the counter ***/
        
$count++;
    }
    
/*** close the file ***/
    
fclose($handle);
    
/*** show the total ***/
    
return $count;
 }

?>