Calculate Full Size of Directory in PHP

This code allows to calculate the full size of a directory using PHP.
Special thanks to: Corne O Kelly

[View All Snippets]
Show Plain Text »
  1. <?php
  2. /**
  3.  * Calculate the full size of a directory
  4.  * @param string $DirectoryPath Directory path
  5.  */
  6. function CalcDirectorySize($DirectoryPath) {
  7.     // I reccomend using a normalize_path function here
  8.     // to make sure $DirectoryPath contains an ending slash
  9.     // To display a good looking size you can use a readable_filesize
  10.     // function.
  11.     $Size = 0;
  12.     $Dir = opendir($DirectoryPath);
  13.     if (!$Dir) return -1;
  14.     while (($File = readdir($Dir)) !== false) {
  15.         // Skip file pointers
  16.         if ($File[0] == ) continue;
  17.         // Go recursive down, or add the file size
  18.         if (is_dir($DirectoryPath . $File)) {
  19.             $Size += CalcDirectorySize($DirectoryPath . $File . DIRECTORY_SEPARATOR);
  20.         }
  21.         else {
  22.             $Size += filesize($DirectoryPath . $File);
  23.         }
  24.     }
  25.     closedir($Dir);
  26.     return $Size;
  27. }
  28. ?>
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