Calculate Full Size of Directory in PHP


/ Published in: PHP
Save to your folder(s)

This code allows to calculate the full size of a directory using PHP.


Copy this code and paste it in your HTML
  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. ?>

URL: www.apphp.com/index.php?snippet=php-calculate-directory-size

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.