How to Count Number of Lines in a File with PHP

By | September 23, 2009

It is a common task to know the size of your files. If you are programming anything using PHP, you should know that there is no exact function to count the number of strings in a file without causing high server load. That’s why I have written a function that uses Linux system command, that works very fast and doesn’t cause any server load. Here it is:

function strcount($filename)
{
if (file_exists($filename))
{
$count=exec(“wc -l $filename”);
return substr($count, 0, strpos($count, ” “));
}
else return 0;
}

Everything seems to be simple, yet usable. Have fun!