Pages

Retrieving a Directory Size

PHP doesn’t currently offer a standard function for retrieving the total size of a directory, a task more often required than retrieving total disk space. And although you could make a system-level call to du using exec() or system(), such functions are often disabled for security reasons. The alternative solution is to write a custom PHP function that is capable of carrying out this task. A recursive function seems particularly well-suited for this task.
function directory_size($directory) {

$directorySize=0;

// Open the directory and read its contents.
if ($dh = @opendir($directory)) {

 // Iterate through each directory entry.
 while (($filename = readdir ($dh))) {
 
  // Filter out some of the unwanted directory entries.
  if ($filename != "." && $filename != "..") {
 
   // File, so determine size and add to total.
   if (is_file($directory."/".$filename))
 
    $directorySize += filesize($directory."/".$filename);
    // New directory, so initiate recursion. */
 
    if (is_dir($directory."/".$filename))
    $directorySize += directory_size($directory."/".$filename);
 
   }
  }
 }
    @closedir($dh);
  return $directorySize;
}

Use :
$directory = "/usr/book/chapter10/";
$totalSize = round((directory_size($directory) / 1048576), 2);
printf("Directory %s: %f MB", $directory: ".$totalSize);
Source : Apress Beginning PHP 5 and MySQL 5, From Novice to Professional