Count files recursive
Returns the entire number of files including the child folders.
Author:
Jonas John
License:
Public Domain
Language:
PHP
Created:
01/21/2007
Updated:
01/21/2007
Tags:
files, file functions, folder, directory functions
function count_files_recursive($path) { // use a normalize_path function here // to make sure $path contains an // ending slash // (-> http://codedump.jonasjohn.de/snippets/normalize_path.htm) $files = 0; // open dir: $dir = opendir($path); if (!$dir){return 0;} while (($file = readdir($dir)) !== false) { if ($file[0] == '.'){ continue; } if (is_dir($path.$file)){ // recursive: $files += count_files_recursive($path.$file.DIRECTORY_SEPARATOR); } else { // increase file count $files++; } } // close dir: closedir($dir); return $files; }
count_files_recursive('data/');
Feel free to leave a message:
Add a comment
I guess you would call it a feature or a bug depending on how you look at it given how ls works.
But I think I'd prefer to count them all!
function count_files($dirname) {
if(is_dir($dirname))
$dir_handle = opendir($dirname);
if(!$dir_handle)
return false;
$files = 0;
while($file = readdir($dir_handle)) {
if($file != "." and $file != "..") {
if(!is_dir($dirname . "/" . $file))
$files++;
else
$files += count_files($dirname . "/" . $file);
}
}
closedir($dir_handle);
return $files;
}
Regards,
Lars