PHP count total files in directory AND subdirectory function -


i need total count of jpg files within specified directory, including it's subdirectories. no sub-sub directories.

structure looks :

 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 function, doesn't work fine counts files in last subdirectory, , total 2x more actual amount of files. (will output 80 if have 40 files in 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; } 

for fun of i've whipped together:

class filefinder {     private $onfound;      private function __construct($path, $onfound, $maxdepth)     {         // onfound gets called @ every file found         $this->onfound = $onfound;         // start iterating         $this->iterate($path, $maxdepth);     }      private function iterate($path, $maxdepth)     {         $d = opendir($path);         while ($e = readdir($d)) {             // skip special folders             if ($e == '.' || $e == '..') { continue; }             $abspath = "$path/$e";             if (is_dir($abspath)) {                 // check $maxdepth first before entering next recursion                 if ($maxdepth != 0) {                     // reduce maximum depth next iteration                     $this->iterate($abspath, $maxdepth - 1);                 }             } else {                 // regular file found, call found handler                 call_user_func_array($this->onfound, array($abspath));             }         }         closedir($d);     }      // helper function instantiate 1 finder object     // return value not important though, because methods private     public static function find($path, $onfound, $maxdepth = 0)     {         return new self($path, $onfound, $maxdepth);     } }  // start finding files (maximum depth 1 folder down)  $count = $bytes = 0; filefinder::find('.', function($file) use (&$count, &$bytes) {     // closure updates count , bytes far     ++$count;     $bytes += filesize($file); }, 1);  echo "nr files: $count; bytes used: $bytes\n"; 

you pass base path, found handler , maximum directory depth (-1 disable). found handler function define outside, gets passed path name relative path given in find() function.

hope makes sense , helps :)


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -