php计算整个目录大小的方法

这篇文章主要介绍了php计算整个目录大小的方法,涉及php递归遍历与文件操作的相关技巧,需要的朋友可以参考下,本文实例讲述了php计算整个目录大小的方法,分享给大家供大家参考,具体实现方法如下:

  1. /**
  2. * Calculate the full size of a directory
  3. *
  4. * @author Jonas John
  5. * @version 0.2
  6. * @link http://www.jonasjohn.de/snippets/php/dir-size.htm
  7. * @param string $DirectoryPath Directory path
  8. */
  9. function CalcDirectorySize($DirectoryPath) {
  10. // I reccomend using a normalize_path function here
  11. // to make sure $DirectoryPath contains an ending slash
  12. // (-> http://www.jonasjohn.de/snippets/php/normalize-path.htm)
  13. // To display a good looking size you can use a readable_filesize
  14. // function.
  15. // (-> http://www.jonasjohn.de/snippets/php/readable-filesize.htm)
  16. $Size = 0;
  17. $Dir = opendir($DirectoryPath);
  18. if (!$Dir)
  19. return -1;
  20. while (($File = readdir($Dir)) !== false) {
  21. // Skip file pointers
  22. if ($File[0] == '.') continue;
  23. // Go recursive down, or add the file size
  24. if (is_dir($DirectoryPath . $File))
  25. $Size += CalcDirectorySize($DirectoryPath . $File . DIRECTORY_SEPARATOR);
  26. else
  27. $Size += filesize($DirectoryPath . $File);
  28. }
  29. closedir($Dir);
  30. return $Size;
  31. }
  32. //使用范例:
  33. $SizeInBytes = CalcDirectorySize('data/');