Count files recursive

Returns the entire number of files including the child folders.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
01/21/2007

Updated:
01/21/2007

Tags:
, , ,


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;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

Bill March 06, 2010 at 19:04
Lars example also handles "." and ".." correctly. The example as given will skip an file whose first character is a "." ... so it doesn't count .htaccess, etc. etc.

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!
Lars_G June 17, 2009 at 01:16
The following gave me a faster result.

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