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
/**
* Return the number of files that resides under a directory.
*
* @return integer
* @param string (required) The directory you want to start in
* @param boolean (optional) Recursive counting. Default to FALSE.
* @param integer (optional) Initial value of file count
*/
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;
}
// Usage:
$nfiles = num_files("/home/kchr", true); // count all files that resides under /home/kchr, including subdirs
$nfiles = num_files("/tmp"); // count the files directly under /tmp
?>