find the size of a directory in php

To find the size of a directory in PHP, we can use the recursiveDirectorySize function below. This function will iterate through all files and subdirectories inside the specified directory and return the total size in bytes.

main.php
function recursiveDirectorySize($dir) {
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) {
        if (!$file->isFile()) continue;
        $size += $file->getSize();
    }

    return $size;
}

// Example Usage
$dir = "/path/to/directory";
$size = recursiveDirectorySize($dir);

echo "Size of directory {$dir}: " . $size . " bytes";
389 chars
16 lines

In this example, we define the recursiveDirectorySize function which takes a single argument $dir representing the directory we want to find the size of. We then initialise a variable $size to 0, then loop through all files iteratively within the specified directory by using the RecursiveDirectoryIterator. Within the loop, we only consider files (not directories) by using the isFile() method, and we accumulate the size of all files in the $size variable. Finally, we return the accumulated size.

To use this function, simply call it with the path to the directory you wish to find the size of. The function will return the size in bytes, which can then be output or manipulated as required.

gistlibby LogSnag