Home >Backend Development >PHP Tutorial >PHP calculates the information of the specified folder (number of folders, number of files, folder size)

PHP calculates the information of the specified folder (number of folders, number of files, folder size)

WBOY
WBOYOriginal
2016-07-25 08:43:26840browse
  1. //The code can also be used to count the number of directories
  2. //Formatted output directory size unit: 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: $path

    ";
  63. echo "Directory size : ".sizeFormat($ar['size'])."
    ";
  64. echo "Number of files: ".$ar['count']."
    ";
  65. echo "Directory technique: ".$ar['dircount']."
    ";
  66. //print_r($ar);
  67. ?>
Copy code

PHP


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn