PHP count total files in directory AND subdirectory function
- by Neoweiter
I need to get a total count of JPG files within a specified directory, including ALL it's subdirectories. No sub-sub directories.
Structure looks like this :
dir1/
2 files
subdir 1/
8 files
total dir1 = 10 files
dir2/
5 files
subdir 1/
2 files
subdir 2/
8 files
total dir2 = 15 files
I have this function, which doesn't work fine as it only counts files in the last subdirectory, and total is 2x more than the actual amount of files. (will output 80 if I have 40 files in the last subdir)
public function count_files($path) {
global $file_count;
$file_count = 0;
$dir = opendir($path);
if (!$dir) return -1;
while ($file = readdir($dir)) :
if ($file == '.' || $file == '..') continue;
if (is_dir($path . $file)) :
$file_count += $this->count_files($path . "/" . $file);
else :
$file_count++;
endif;
endwhile;
closedir($dir);
return $file_count;
}