PHP count total files in directory AND subdirectory function

Posted by Neoweiter on Stack Overflow See other posts from Stack Overflow or by Neoweiter
Published on 2012-06-05T10:07:26Z Indexed on 2012/06/05 10:40 UTC
Read the original article Hit count: 333

Filed under:
|
|
|
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about file