What potential pitfalls should be considered when using recursion in PHP functions for directory manipulation?

When using recursion in PHP functions for directory manipulation, potential pitfalls to consider include the risk of infinite loops if the termination condition is not properly defined, the possibility of exceeding the maximum stack depth if the recursion goes too deep, and the performance implications of recursive calls for large directory structures. To address these issues, it's important to carefully plan the termination condition, optimize the recursive function to minimize unnecessary calls, and consider alternative non-recursive approaches for handling directory manipulation tasks.

function processDirectory($dir) {
    if (!is_dir($dir)) {
        return;
    }

    $files = scandir($dir);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                processDirectory($path); // Recursive call
            } else {
                // Process file
            }
        }
    }
}

// Usage
processDirectory('/path/to/directory');