directory_size() function for PHP

Here’s a quick PHP function that returns the sum of all filesizes in a directory. It does this by looping through all files it finds in the directory you pass to it. If a subdirectory is found the function calls itself recursively.

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. Inputs:
  4. $dir    The directory to check
  5. Outputs:
  6. The total file size of all files in $dir
  7. */
  8. {
  9. $retval = 0;
  10. $dirhandle = opendir($dir);
  11. while ($file = readdir($dirhandle))
  12. {
  13. if ($file!=“.” && $file!=“..”)
  14. {
  15. if (is_dir($dir.“/”.$file))
  16. {
  17. $retval = $retval + directory_size($dir.“/”.$file);
  18. }
  19. else
  20. {
  21. $retval = $retval + filesize($dir.“/”.$file);
  22. }
  23. }
  24. }
  25. closedir($dirhandle);
  26. return $retval;
  27. }

One thing to note is that the file size returned is in bytes.  If you want to get it in something more friendly you’ll have to do some math.

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

Leave a Reply