PHP function - directory_size()
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")
-
function directory_size($dir)
-
/* Return the file size for files in directory
-
-
Inputs:
-
$dir The directory to check
-
Outputs:
-
The total file size of all files in $dir
-
*/
-
{
-
$retval = 0;
-
{
-
if ($file!="." && $file!="..")
-
{
-
{
-
$retval = $retval + directory_size($dir."/".$file);
-
}
-
else
-
{
-
}
-
}
-
}
-
-
return $retval;
-
}
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.
-
$total_file_size = directory_size("/directory");
-
$file_size_suffix = "bytes";
-
if ($total_file_size>1024)
-
{
-
$file_size_suffix = "kb";
-
$total_file_size = $total_file_size / 1024;
-
}
-
if ($total_file_size>1024)
-
{
-
$file_size_suffix = "mb";
-
$total_file_size = $total_file_size / 1024;
-
}
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.



