Count Number of Files in Directory and Subdirectories

Count number of files in a directory and it’s subdirectories.

Use the following code to count number of files.

[php]

<h1>Count Number of Files in Directory and Subdirectories</h1>
<?php
$dirnam=dirname(__FILE__); //No Trailing Slash//

function count_files($dirpath, &$count)
{
$directorynames = glob($dirpath.’/*’);
if(!empty($directorynames))
{
foreach($directorynames as $directoryname)
{
if(is_dir($directoryname))
{
$count[‘dirs’]++;
count_files($directoryname, $count);
}
if(is_file($directoryname))
{
$count[‘files’]++;

//$path_parts=pathinfo($directoryname, PATHINFO_EXTENSION);
$path_extension=pathinfo($directoryname, PATHINFO_EXTENSION);
//$path_extension=$path_parts[‘extension’];

$count[$path_extension]++;

}
}
}

}

count_files($dirnam, $count);
echo "<h2>Total Files</h2>";
foreach($count AS $count_keys=>$count_value)
{
echo "<b>$count_keys</b> $count_value<br>";
}
echo "<hr>";
?>

[/php]

Above code will output total number of directories, files and also number of files of each extension.

Leave a Comment