Handy little function that returns the number of files (not directories) that exists under a directory.
Choose if you want the function to recurse through sub-directories with the second parameter -
the default mode (false) is just to count the files directly under the supplied path.
<?php
function num_files($dir, $recursive=false, $counter=0) {
static $counter;
if(is_dir($dir)) {
if($dh = opendir($dir)) {
while(($file = readdir($dh)) !== false) {
if($file != "." && $file != "..") {
$counter = (is_dir($dir."/".$file)) ? num_files($dir."/".$file, $recursive, $counter) : $counter+1;
}
}
closedir($dh);
}
}
return $counter;
}
$nfiles = num_files("/home/kchr", true); $nfiles = num_files("/tmp"); ?>