I ran into an issue earlier today. I needed to get the size of a directory, which Laravels \File class should have no problem doing.

Unfortunately, the code is doing exactly what it is told and not what we want it to do. Consider the following:

\File::size(storage_path('app/files/'))

You might think that this will return the total size for that folder, but on most Linux systems it will simply return 4096. This cant be right, I have at least a dozen MB worth of data stored there. It turns out it is simply returning the size of the directory itself on the disk, and not the size of all of the contents.

We can make it do what we want though, we just need to have it iterate over the files already there and return the sum of their sizes.

Here is a quick macro to do that:

/**
 * Returns the total size for all files in a directory
 *
 * @param string $dirName
 * @return int
 */
\File::macro('dirSize', function(string $dirName): int {
    if (!\File::isDirectory($dirName)) {
        throw new \InvalidArgumentException('Directory is invalid');
    }
    $bytesSum = 0;
    foreach (\File::files($dirName) as $file) {
        $bytesSum += $file->getSize();
    }
    return $bytesSum;
});