PHP function - directory_size()

Posted in Programming  
E-Mail This Post/Page   

Here's a quick PHP function that will return the size of all files in a directory.

To use: pass the directory you want to check as the only variable, eg: directory_size("/home/web/directory")

PHP:
  1. function directory_size($dir)
  2. /*  Return the file size for files in directory
  3.    
  4.     Inputs:
  5.         $dir    The directory to check
  6.     Outputs:
  7.         The total file size of all files in $dir
  8.     */
  9.     {
  10.     $retval = 0;
  11.     $dirhandle = opendir($dir);
  12.     while ($file = readdir($dirhandle))
  13.         {
  14.         if ($file!="." && $file!="..")
  15.             {
  16.             if (is_dir($dir."/".$file))
  17.                 {
  18.                 $retval = $retval + directory_size($dir."/".$file);
  19.                 }
  20.             else
  21.                 {
  22.                 $retval = $retval + filesize($dir."/".$file);
  23.                 }
  24.             }      
  25.         }
  26.     closedir($dirhandle);
  27.  
  28.     return $retval;
  29.     }

Note that the function calls itself recursively so all subdirectories are included in the total.

To get it in a little more human friendly format, I use the following code.

PHP:
  1. $total_file_size = directory_size("/directory");
  2. $file_size_suffix = "bytes";
  3. if ($total_file_size>1024)
  4.     {
  5.     $file_size_suffix = "kb";
  6.     $total_file_size = $total_file_size / 1024;
  7.     }
  8. if ($total_file_size>1024)
  9.     {
  10.     $file_size_suffix = "mb";
  11.     $total_file_size = $total_file_size / 1024;
  12.     }
  13. $total_file_size = number_format($total_file_size, 2)." ".$file_size_suffix;

This will take '82358432' and change it to '78.54 mb'. And if you're dealing with really large directories, it would be simple to extend it beyond megabytes by dividing by 1024 as many times as needed to get to the unit you're after.

Credit: This script is loosely based on this one at alt-php-faq.org.

file_get_contents function for PHP 4
is_safe_mode function for PHP
Benchmarking PHP: Inserting text with include(), require(), or get_file_contents()
A routine to create GUIDs in PHP
Javascript time formatting function

Leave a Comment