PHP – get the size of a directory

2019-01-12 11:45发布

问题:

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.

There already was a question about this on SO, but it's three years old and the solutions are outdated.(Nowadays fopen is disabled for security reasons.)

回答1:

Is the RecursiveDirectoryIterator available to you?

$bytes = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $i) 
{
  $bytes += $i->getSize();
}


回答2:

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;
}