How can one determine the total size of a folder in PHP and set a limit for it?

To determine the total size of a folder in PHP, you can recursively iterate through all files and subfolders within the directory and sum up their sizes. To set a limit for the folder size, you can compare the total size with the specified limit and take appropriate action if the limit is exceeded.

function getFolderSize($dir){
    $total_size = 0;
    $files = scandir($dir);

    foreach($files as $file){
        if($file != "." && $file != ".."){
            if(is_dir($dir . '/' . $file)){
                $total_size += getFolderSize($dir . '/' . $file);
            } else {
                $total_size += filesize($dir . '/' . $file);
            }
        }
    }

    return $total_size;
}

$folder = 'path/to/folder';
$limit = 1000000; // 1MB limit

$folder_size = getFolderSize($folder);

if($folder_size > $limit){
    echo "Folder size exceeds limit!";
} else {
    echo "Folder size is within limit.";
}