How to get the size of a directory in PHP?

You can use the following PHP code to get the size of a directory:

function getDirectorySize($path) { $totalSize = 0; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); foreach ($iterator as $file) { if ($file->isFile()) { $totalSize += $file->getSize(); } } return $totalSize; } $directoryPath = "/path/to/directory"; $size = getDirectorySize($directoryPath); echo "Size of directory: " . $size . " bytes";

This code defines a function getDirectorySize() which takes the directory path as a parameter and recursively iterates through each file in the directory and its subdirectories. The RecursiveDirectoryIterator class is used in conjunction with the RecursiveIteratorIterator class to achieve this. The function retrieves the size of each file using the getSize() method and adds it to the totalSize variable. Finally, the function returns the total size in bytes, which can be printed or used as needed.