欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP计算指定文件夹的信息(文件夹数,文件数,文件夹大小)

程序员文章站 2024-01-10 09:59:40
...
  1. //代码也可以用于统计目录数
  2. //格式化输出目录大小 单位:Bytes,KB,MB,GB
  3. function getDirectorySize($path)
  4. {
  5. $totalsize = 0;
  6. $totalcount = 0;
  7. $dircount = 0;
  8. if ($handle = opendir ($path))
  9. {
  10. while (false !== ($file = readdir($handle)))
  11. {
  12. $nextpath = $path . '/' . $file;
  13. if ($file != '.' && $file != '..' && !is_link ($nextpath))
  14. {
  15. if (is_dir ($nextpath))
  16. {
  17. $dircount++;
  18. $result = getDirectorySize($nextpath);
  19. $totalsize += $result['size'];
  20. $totalcount += $result['count'];
  21. $dircount += $result['dircount'];
  22. }
  23. elseif (is_file ($nextpath))
  24. {
  25. $totalsize += filesize ($nextpath);
  26. $totalcount++;
  27. }
  28. }
  29. }
  30. }
  31. closedir ($handle);
  32. $total['size'] = $totalsize;
  33. $total['count'] = $totalcount;
  34. $total['dircount'] = $dircount;
  35. return $total;
  36. }
  37. function sizeFormat($size)
  38. {
  39. $sizeStr='';
  40. if($size {
  41. return $size." bytes";
  42. }
  43. else if($size {
  44. $size=round($size/1024,1);
  45. return $size." KB";
  46. }
  47. else if($size {
  48. $size=round($size/(1024*1024),1);
  49. return $size." MB";
  50. }
  51. else
  52. {
  53. $size=round($size/(1024*1024*1024),1);
  54. return $size." GB";
  55. }
  56. }
  57. $path="/home/www/htdocs";
  58. $ar=getDirectorySize($path);
  59. echo "

    路径 : $path

    ";
  60. echo "目录大小 : ".sizeFormat($ar['size'])."
    ";
  61. echo "文件数 : ".$ar['count']."
    ";
  62. echo "目录术 : ".$ar['dircount']."
    ";
  63. //print_r($ar);
  64. ?>
复制代码

PHP