Count files recursive

Returns the entire number of files including all child directories.

function count_files($path) {
 
    // (Ensure that the path contains an ending slash)
 
    $file_count = 0;
 
    $dir_handle = opendir($path);
 
    if (!$dir_handle) return -1;
 
    while ($file = readdir($dir_handle)) {
 
        if ($file == '.' || $file == '..') continue;
 
        if (is_dir($path . $file)){      
            $file_count += count_files($path . $file . DIRECTORY_SEPARATOR);
        }
        else {
            $file_count++; // increase file count
        }
    }
 
    closedir($dir_handle);
 
    return $file_count;
}
Snippet Details



count_files('./my_awesome_folder/');

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Jonas March 11, 2011 at 19:42
I fixed and updated the code snippet - thanks Lars & Bill!
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