PHP – get the size of a directory

前端 未结 2 1533
夕颜
夕颜 2020-12-04 02:44

What is the best way to get the size of a directory in PHP? I\'m looking for a lightweight way to do this since the directories I\'ll use this for are pretty huge.

T

相关标签:
2条回答
  • 2020-12-04 03:31

    You could try the execution operator with the unix command du:

    $output = du -s $folder;

    FROM: http://www.darian-brown.com/get-php-directory-size/

    Or write a custom function to total the filesize of all the files in the directory:

    function getDirectorySize($path)
    {
      $totalsize = 0;
      $totalcount = 0;
      $dircount = 0;
     if($handle = opendir($path))
     {
        while (false !== ($file = readdir($handle)))
        {
          $nextpath = $path . '/' . $file;
          if($file != '.' && $file != '..' && !is_link ($nextpath))
          {
            if(is_dir($nextpath))
           {
             $dircount++;
             $result = getDirectorySize($nextpath);
             $totalsize += $result['size'];
              $totalcount += $result['count'];
             $dircount += $result['dircount'];
           }
           else if(is_file ($nextpath))
           {
              $totalsize += filesize ($nextpath);
              $totalcount++;
           }
         }
       }
     }
     closedir($handle);
     $total['size'] = $totalsize;
     $total['count'] = $totalcount;
     $total['dircount'] = $dircount;
     return $total;
    }
    
    0 讨论(0)
  • 2020-12-04 03:34

    Is the RecursiveDirectoryIterator available to you?

    $bytes = 0;
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($iterator as $i) 
    {
      $bytes += $i->getSize();
    }
    
    0 讨论(0)
提交回复
热议问题