What is the best practice for deleting a directory with contents in PHP?

When deleting a directory with contents in PHP, it is best practice to recursively delete all files and subdirectories within the directory before removing the directory itself. This ensures that all contents are properly removed and prevents any errors from occurring.

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }
    
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        
        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }
    
    return rmdir($dir);
}

// Usage
$directory = 'path/to/directory';
deleteDirectory($directory);