What are some best practices for managing directory deletion in PHP to avoid "Permission denied" errors?

When deleting directories in PHP, it is important to ensure that the script has the necessary permissions to delete the directory and its contents. One way to avoid "Permission denied" errors is to check if the directory exists and is writable before attempting to delete it. Additionally, using functions like `rmdir()` or `unlink()` can help handle directory deletion more efficiently and securely.

$directory = 'path/to/directory';

if (is_dir($directory) && is_writable($directory)) {
    $files = glob($directory . '/*');
    
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }

    rmdir($directory);
    echo 'Directory deleted successfully.';
} else {
    echo 'Unable to delete directory. Check permissions.';
}