php 文件目录大小统计函数

文件夹大小统计主要是计算文件夹里面的文件大小然后相加之后再利用函数进行统计了,统计文件大小函数我们使用php filesize函数了,其它的全用目录相关的处理函数,下面一起来看看.

计算文件夹的大小,包括子文件夹,格式化输出文件夹大小、文件数、子文件夹数信息,代码如下:

  1. <?php
  2. //代码也可以用于统计目录数
  3. //格式化输出目录大小 单位:Bytes,KB,MB,GB
  4. function getDirectorySize($path)
  5. {
  6. $totalsize = 0;
  7. $totalcount = 0;
  8. $dircount = 0;
  9. if ($handle = opendir ($path))
  10. {
  11. while (false !== ($file = readdir($handle)))
  12. {
  13. $nextpath = $path . '/' . $file;
  14. if ($file != '.' && $file != '..' && !is_link ($nextpath))
  15. {
  16. if (is_dir ($nextpath))
  17. {
  18. $dircount++;
  19. $result = getDirectorySize($nextpath);
  20. $totalsize += $result['size'];
  21. $totalcount += $result['count'];
  22. $dircount += $result['dircount'];
  23. }
  24. elseif (is_file ($nextpath))
  25. {
  26. $totalsize += filesize ($nextpath);
  27. $totalcount++;
  28. }//开源代码phpfensi.com
  29. }
  30. }
  31. }
  32. closedir ($handle);
  33. $total['size'] = $totalsize;
  34. $total['count'] = $totalcount;
  35. $total['dircount'] = $dircount;
  36. return $total;
  37. }
  38. ?>

PHP中计算文件目录大小其实主要是用到"filesize"函数,通过递归的方法计算每个文件的大小,再计算他们的和即是整个文件目录的大小.

因为直接返回的文件大小是以字节为单位的,所以我们一般还要经过换算得到我们常见得大小,以下是单位换算的函数,代码如下:

  1. function sizeFormat($size)
  2. {
  3. $sizeStr='';
  4. if($size<1024)
  5. {
  6. return $size." bytes";
  7. }
  8. else if($size<(1024*1024))
  9. {
  10. $size=round($size/1024,1);
  11. return $size." KB";
  12. }
  13. else if($size<(1024*1024*1024))
  14. {
  15. $size=round($size/(1024*1024),1);
  16. return $size." MB";
  17. }
  18. else
  19. {
  20. $size=round($size/(1024*1024*1024),1);
  21. return $size." GB";
  22. }
  23. }
  24. $path="/home/www/htdocs";
  25. $ar=getDirectorySize($path);
  26. echo "<h4>路径 : $path</h4>";
  27. echo "目录大小 : ".sizeFormat($ar['size'])."<br>";
  28. echo "文件数 : ".$ar['count']."<br>";
  29. echo "目录术 : ".$ar['dircount']."<br>";
  30. //print_r($ar);

后面附一个单位函数,该函数最主要的是根据文件的字节数,判断应当选择的统计单位,也就是说一个文件用某一单位比如MB,那么该文件肯定小于1GB,否则当然要用GB作为单位了,而且文件要大于KB,不然的话得用更小的单位统计,该函数代码如下:

  1. //size() 统计文件大小
  2. function size($byte)
  3. {
  4. if($byte < 1024) {
  5. $unit="B";
  6. }
  7. else if($byte < 10240) {
  8. $byte=round_dp($byte/1024, 2);
  9. $unit="KB";
  10. }
  11. else if($byte < 102400) {
  12. $byte=round_dp($byte/1024, 2);
  13. $unit="KB";
  14. }
  15. else if($byte < 1048576) {
  16. $byte=round_dp($byte/1024, 2);
  17. $unit="KB";
  18. }
  19. else if ($byte < 10485760) {
  20. $byte=round_dp($byte/1048576, 2);
  21. $unit="MB";
  22. }
  23. else if ($byte < 104857600) {
  24. $byte=round_dp($byte/1048576,2);
  25. $unit="MB";
  26. }
  27. else if ($byte < 1073741824) {
  28. $byte=round_dp($byte/1048576, 2);
  29. $unit="MB";
  30. }
  31. else {
  32. $byte=round_dp($byte/1073741824, 2);
  33. $unit="GB";
  34. }
  35. $byte .= $unit;
  36. return $byte;
  37. }
  38. function round_dp($num , $dp)
  39. {
  40. $sh = pow(10 , $dp);
  41. return (round($num*$sh)/$sh);
  42. }