title: PHP count total files in directory AND subdirectory function
body: <p>I need to get a total count of JPG files within a specified directory, including ALL it's subdirectories. No sub-sub directories.</p>
  
  <p>Structure looks like this :</p>
  
  <pre>
  dir1/
  2 files  
     subdir 1/
         8 files
  </pre>
  
  <p>total <strong>dir1</strong> = 10 files</p>
  
  <pre>
  dir2/ 
      5 files  
      subdir 1/ 
          2 files  
      subdir 2/ 
          8 files
  </pre>
  
  <p>total <strong>dir2</strong> = 15 files</p>
  
  <p>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. <em>(will output 80 if I have 40 files in the last subdir)</em></p>
  
  <pre><code>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-&gt;count_files($path . "/" . $file);
      else :
          $file_count++;
      endif;
  endwhile;
  
  closedir($dir);
  return $file_count;
  }
  </code></pre>