Are there any potential pitfalls when using the rmdir() function in PHP to delete directories?

One potential pitfall when using the rmdir() function in PHP to delete directories is that it will only delete empty directories. If the directory contains any files or subdirectories, the function will fail. To overcome this limitation, you can use a recursive function to delete all files and subdirectories within the directory before attempting to delete the directory itself.

function deleteDirectory($dir) {
    if (!file_exists($dir) || !is_dir($dir)) {
        return false;
    }
    
    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        (is_dir("$dir/$file")) ? deleteDirectory("$dir/$file") : unlink("$dir/$file");
    }
    
    return rmdir($dir);
}

// Example usage
$directory = "path/to/directory";
if (deleteDirectory($directory)) {
    echo "Directory deleted successfully.";
} else {
    echo "Failed to delete directory.";
}