How to count files in folder with PHP- Linux file count

I’ve heard of issues where a large number of iNodes (files) were causing problems on servers, blocking file read and write access among other things. The first question in this situation is where the files are. Chances are there are a lot of files piled up somewhere, that you don’t need. On Linux you can run file counts various ways from command line. I came up with my own solution using PHP.

Using this code will give you some nice control over which directories are listed, and display it in a pretty format. Here is how you can count files in a folder with PHP.

function GetFileCount($dir,$level,$minCountToDisplay){
 
    if (is_dir($dir))
    {
        // this is a directory
 
        // init file count value
        $fileCount = 0;
        if ($dh = opendir($dir))
        {
            // iterate through files in this directory
            while (($file = readdir($dh)) !== false)
            {
                // skip moving up the directory tree, only go down!
                if($file != '..' && $file != '.'){
                    // recursive file counting
                    $fileCount+=GetFileCount($dir."/".$file,$level+1,$minCountToDisplay);
                }
            }
            // clean up
            closedir($dh);
        } else {
            // something went wrong, move on
            echo("Failed opening directory: $dir\n");
        }
        // only print the file count if it meets our minimum value
        if($fileCount >= $minCountToDisplay){
            // str_pad for a clean layout
            echo(str_pad($fileCount,10).$dir."\n");
        }
        return $fileCount+1;
 
    } else {
        // not a directory
        return 1;
    }
}
 
// default threshold to display a directory's file count
$minCountToDisplay = 0;
 
// get command line params if any
// ie: php getfilecounts.php
// or: php getfilecounts.php min=500
 
parse_str(implode('&', array_slice($argv, 1)), $a);
if(isset($a['min']) && is_numeric($a['min']) && $a['min'] > 0){
    $minCountToDisplay = $a['min'];
}
 
// set working directory to the one this file is in.
chdir ( dirname(__FILE__) );
echo "Current working directory: ";
echo getcwd()."\n";
 
// display file counts
GetFileCount(getcwd(),0,$minCountToDisplay);

The code is self-documented and should pretty straightforward. Essentially you can run this from command line and recursively drill down through directories displaying the number of files and directories in each. You can even tell it with a command line parameter what the minimum count of files should be for it to print to screen.