How can the contents of a folder be deleted before attempting to delete the folder itself in PHP?

To delete the contents of a folder before attempting to delete the folder itself in PHP, you can recursively delete all files and subfolders within the target folder. This ensures that the folder is empty before attempting to delete it.

function deleteFolderContents($dir) {
    $files = glob($dir . '/*');
    
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteFolderContents($file);
            rmdir($file);
        } else {
            unlink($file);
        }
    }
}

$folderPath = 'path/to/folder';
deleteFolderContents($folderPath);
rmdir($folderPath);