2

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.)

Community
  • 1
  • 1
js-coder
  • 8,134
  • 9
  • 42
  • 59
  • fopen is disabled in the config, but can be turned on. Do you not have access to the server config? – Neil Aitken Feb 06 '12 at 16:29
  • 1
    @NeilAitken It's disabled for security reasons, so I won't enable it for sure! – js-coder Feb 06 '12 at 16:30
  • Are you on a shared host that has explicitly disabled it? As the default config is to have it enabled. There aren't security implications to fopen if it's a dedicated server, but I can see why shared hosts may want it off just to be sure. – Neil Aitken Feb 06 '12 at 16:33

2 Answers2

6

Is the RecursiveDirectoryIterator available to you?

$bytes = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $i) 
{
  $bytes += $i->getSize();
}
Rob Agar
  • 12,337
  • 5
  • 48
  • 63
  • There's a more comprehensive version of this at http://stackoverflow.com/a/21409562/442022. – colan Mar 07 '17 at 16:52
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;
}
Warren J Thompson
  • 408
  • 1
  • 7
  • 19
  • It looks like the SO code blocks them but you need backticks around the unix command... one before the du and one before the semicolon. – Night Owl Feb 06 '12 at 16:33