当前位置:Gxlcms > PHP教程 > PHP计算指定文件夹的信息(文件夹数,文件数,文件夹大小)

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

时间:2021-07-01 10:21:17 帮助过:16人阅读

  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<1024)
  41. {
  42. return $size." bytes";
  43. }
  44. else if($size<(1024*1024))
  45. {
  46. $size=round($size/1024,1);
  47. return $size." KB";
  48. }
  49. else if($size<(1024*1024*1024))
  50. {
  51. $size=round($size/(1024*1024),1);
  52. return $size." MB";
  53. }
  54. else
  55. {
  56. $size=round($size/(1024*1024*1024),1);
  57. return $size." GB";
  58. }
  59. }
  60. $path="/home/www/htdocs";
  61. $ar=getDirectorySize($path);
  62. echo "

    路径 : $path

    ";
  63. echo "目录大小 : ".sizeFormat($ar['size'])."
    ";
  64. echo "文件数 : ".$ar['count']."
    ";
  65. echo "目录术 : ".$ar['dircount']."
    ";
  66. //print_r($ar);
  67. ?>

PHP

人气教程排行