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

jerry thinkphp 2015年11月18日 收藏
计算文件夹的大小,包括子文件夹,格式化输出文件夹大小、文件数、子文件夹数信息。
  1. <?
  2. //代码也可以用于统计目录数
  3. //格式化输出目录大小 单位:Bytes,KB,MB,GB
  4.  
  5. function getDirectorySize($path)
  6. {
  7.   $totalsize = 0;
  8.   $totalcount = 0;
  9.   $dircount = 0;
  10.   if ($handle = opendir ($path))
  11.   {
  12.     while (false !== ($file = readdir($handle)))
  13.     {
  14.       $nextpath = $path . '/' . $file;
  15.       if ($file != '.' && $file != '..' && !is_link ($nextpath))
  16.       {
  17.         if (is_dir ($nextpath))
  18.         {
  19.           $dircount++;
  20.           $result = getDirectorySize($nextpath);
  21.           $totalsize += $result['size'];
  22.           $totalcount += $result['count'];
  23.           $dircount += $result['dircount'];
  24.         }
  25.         elseif (is_file ($nextpath))
  26.         {
  27.           $totalsize += filesize ($nextpath);
  28.           $totalcount++;
  29.         }
  30.       }
  31.     }
  32.   }
  33.   closedir ($handle);
  34.   $total['size'] = $totalsize;
  35.   $total['count'] = $totalcount;
  36.   $total['dircount'] = $dircount;
  37.   return $total;
  38. }
  39.  
  40. function sizeFormat($size)
  41. {
  42.     $sizeStr='';
  43.     if($size<1024)
  44.     {
  45.         return $size." bytes";
  46.     }
  47.     else if($size<(1024*1024))
  48.     {
  49.         $size=round($size/1024,1);
  50.         return $size." KB";
  51.     }
  52.     else if($size<(1024*1024*1024))
  53.     {
  54.         $size=round($size/(1024*1024),1);
  55.         return $size." MB";
  56.     }
  57.     else
  58.     {
  59.         $size=round($size/(1024*1024*1024),1);
  60.         return $size." GB";
  61.     }
  62.  
  63. }
  64.  
  65. $path="/home/www/htdocs";
  66. $ar=getDirectorySize($path);
  67.  
  68. echo "<h4>路径 : $path</h4>";
  69. echo "目录大小 : ".sizeFormat($ar['size'])."<br>";
  70. echo "文件数 : ".$ar['count']."<br>";
  71. echo "目录术 : ".$ar['dircount']."<br>";
  72.  
  73. //print_r($ar);
  74. ?>