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.php389 chars16 linesIn 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