What are potential pitfalls when using PHP to recursively delete directories based on a specific prefix?

Potential pitfalls when using PHP to recursively delete directories based on a specific prefix include accidentally deleting unintended directories that match the prefix, lack of proper error handling leading to unexpected behavior, and potential security risks if user input is not properly sanitized.

function deleteDirectoriesWithPrefix($directory, $prefix) {
    if (!is_dir($directory)) {
        return;
    }

    $files = scandir($directory);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $fullPath = $directory . '/' . $file;
            if (is_dir($fullPath) && strpos($file, $prefix) === 0) {
                deleteDirectoriesWithPrefix($fullPath, $prefix);
                rmdir($fullPath);
            }
        }
    }
}

// Usage example
deleteDirectoriesWithPrefix('/path/to/directory', 'prefix_');