Count files recursive in PHP

This code teturns the entire number of files including all child directories.

[View All Snippets]
Show Plain Text »
  1. <?php
  2. function count_files($path) {
  3.     // (Ensure that the path contains an ending slash)
  4.     $file_count = 0;
  5.     $dir_handle = opendir($path);
  6.     if (!$dir_handle) return -1;
  7.     while ($file = readdir($dir_handle)) {
  8.         if ($file == "." || $file == "..") continue;
  9.         if (is_dir($path . $file)){      
  10.             $file_count += count_files($path . $file . DIRECTORY_SEPARATOR);
  11.         }
  12.         else {
  13.             $file_count++; // increase file count
  14.         }
  15.     }
  17.     closedir($dir_handle);
  19.     return $file_count;
  20. }
  22. count_files("./my_folder/");
  23. ?>

Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory

Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.

Quick Registration with: Facebook / Google