Count files recursive

Returns the entire number of files including all child directories.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;
}
//Example:
count_files('./my_awesome_folder/');
X

Url: http://www.jonasjohn.de/snippets/php/count-files-recursive.htm

Language: PHP | User: ShareMySnippets | Created: Oct 16, 2013