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

php获取文件夹信息的统计函数

程序员文章站 2022-06-10 17:24:03
...
  1. //统计文件夹的相关信息
  2. //统计目录数
  3. //格式化输出目录大小 单位:Bytes,KB,MB,GB
  4. function getFolderSize($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 = getFolderSize($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. }
  29. }
  30. }
  31. }
  32. closedir ($handle);
  33. $total['size'] = $totalsize;
  34. $total['count'] = $totalcount;
  35. $total['dircount'] = $dircount;
  36. return $total;
  37. }
  38. //格式化输出信息

  39. function sizeFormat($size)
  40. {
  41. $sizeStr='';
  42. if($size {
  43. return $size." bytes";
  44. }
  45. else if($size {
  46. $size=round($size/1024,1);
  47. return $size." KB";
  48. }
  49. else if($size {
  50. $size=round($size/(1024*1024),1);
  51. return $size." MB";
  52. } bbs.it-home.org
  53. else
  54. {
  55. $size=round($size/(1024*1024*1024),1);
  56. return $size." GB";
  57. }
  58. }
  59. $path="/var/www";
  60. $ar=getFolderSize($path);
  61. echo "

    您查看的路径 : $path

    ";
  62. echo "目录大小 : ".sizeFormat($ar['size'])."
    ";
  63. echo "文件数 : ".$ar['count']."
    ";
  64. echo "目录数 : ".$ar['dircount']."
    ";
  65. //输出

  66. //print_r($ar);
  67. ?>
复制代码

例2,php获取文件夹大小的函数

  1. // 获取文件夹大小
  2. function getDirSize($dir)
  3. {
  4. $handle = opendir($dir);
  5. while (false!==($FolderOrFile = readdir($handle)))
  6. {
  7. if($FolderOrFile != "." && $FolderOrFile != "..")
  8. {
  9. if(is_dir("$dir/$FolderOrFile"))
  10. {
  11. $sizeResult += getDirSize("$dir/$FolderOrFile");
  12. }
  13. else
  14. {
  15. $sizeResult += filesize("$dir/$FolderOrFile");
  16. }
  17. }
  18. }
  19. closedir($handle);
  20. return $sizeResult;
  21. }
  22. // 单位自动转换函数
  23. function getRealSize($size)
  24. {
  25. $kb = 1024; // Kilobyte
  26. $mb = 1024 * $kb; // Megabyte
  27. $gb = 1024 * $mb; // Gigabyte
  28. $tb = 1024 * $gb; // Terabyte
  29. if($size {
  30. return $size." B";
  31. }
  32. else if($size {
  33. return round($size/$kb,2)." KB";
  34. }
  35. else if($size {
  36. return round($size/$mb,2)." MB";
  37. }
  38. else if($size {
  39. return round($size/$gb,2)." GB";
  40. }
  41. else
  42. {
  43. return round($size/$tb,2)." TB";
  44. }
  45. }
  46. echo getRealSize(getDirSize('目录路径'));
  47. ?>
复制代码