PHP: How to calculate total size of a folder (in bytes)

Updated: January 11, 2024 By: Guest Contributor Post a comment

Overview

In this tutorial, we are going to walk through the process of calculating the total size of a folder in bytes with PHP. Understanding how to manipulate file system operations is a critical skill for many web applications, whether you are trying to monitor server storage, manage user uploads, or provide analytics on file usage, knowing how to perform this operation can be very useful.

To calculate the total size of a folder, we will primarily make use of the PHP’s directory iteration capabilities along with filesize functions to accumulate the size of each individual file within a directory and its subdirectories.

Preparation

The first step is to ensure that your PHP environment is set up and that you have the permissions required to read the files on your server. For the sake of this tutorial, we will assume you are running PHP 7.0 or higher.

Basic Concept

To calculate the total size of a folder, we need to:

  • Open the directory
  • Iterate through all the files and subdirectories within the directory
  • Recursively repeat the process for each subdirectory
  • Get the file size for each file
  • Accumulate the sizes to get the total

Implementing the Logic

This is an example function that recursively calculates the size of a directory:

<?php

function folderSize($dir) {
    $size = 0;
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) {
        if ($file->isFile()) {
            $size += $file->getSize();
        }
    }
    return $size;
}

?>

The function folderSize uses PHP’s SPL (Standard PHP Library) iterators to traverse the directory structure. The RecursiveDirectoryIterator provides an interface to iterate through directories and their files, and the RecursiveIteratorIterator allows iterating over it recursively.

Handling Edge Cases

While the above code covers the basic functionality, there are some circumstances you should consider, namely:

  • Permissions: Make sure your PHP process has read access to the files and directories you are trying to size up. Otherwise, you would need to handle the Permission denied errors.
  • Hidden Files: Linux/Unix systems have hidden files (e.g., .htaccess), you may want to decide if to include these in your size calculations.
  • Symbolic Links: You may encounter symbolic links, which you might want to treat differently because a symlink’s size is its path length, not what it points to.
  • Disk Usage vs. File Size: Disk space is typically allocated in blocks, so the actual disk usage could slightly differ from the sum of file sizes.

Optimized Function

To make our function robust, we will add error handling and an option to exclude symlinks:

<?php

function folderSize($dir, $excludeSymlinks = true) {
    $size = 0;
    if (!is_readable($dir)) return 0; // Check if directory is readable
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) {
        if ($excludeSymlinks && $file->isLink()) {
            continue;
        }
        if ($file->isFile()) {
            $size += $file->getSize();
        }
    }
    return $size;
}

?>

Note that is_readable is used to check permissions. To include symbolic links, you just need to call folderSize with the second parameter set to false.

Usage Example

To use this function, simply call it with a directory path:

<?php

$folderPath = '/path/to/your/directory';
$totalSize = folderSize($folderPath);
echo 'Total Size: ' . $totalSize . ' bytes';

?>

Formatting the Result

Chances are you want to show the folder size to users in a more friendly format such as KB, MB, or GB. Here’s a helper function to do that:

<?php

function formatSizeUnits($bytes) {
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }
    return $bytes;
}

?>

Now you can output the size in a human-readable format:

<?php

echo 'Total Size: ' . formatSizeUnits($totalSize);

?>

Conclusion

Calculating the size of a folder using PHP can seem daunting at first, but with the power of recursive iterators and a few lines of code, it becomes a fairly straightforward task. This tutorial helps PHP developers utilize the filesystem capabilities to measure the size of directories, ensure error handling, and output the size in a human-readable format. With these tools and functions, you can begin incorporating file and folder size metrics into your web applications.

Remember to test your script on different server environments and account for various edge cases. As a server administrator or developer, it’s also good practice to routinely check and update permissions to maintain security and functionality.

By adding these functionalities to your PHP utility belt, you will be able to create more dynamic and capable web applications, and more effectively manage file-related tasks.