Are there any potential pitfalls to using recursive functions in PHP for directory operations?

One potential pitfall of using recursive functions in PHP for directory operations is the risk of running into memory limitations when dealing with deeply nested directories or a large number of files. To mitigate this issue, you can implement a depth limit or use an iterative approach instead of a recursive one.

function listFiles($dir, $depth = 0, $maxDepth = 10) {
    if ($depth > $maxDepth) {
        return;
    }

    $files = scandir($dir);
    
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') {
            continue;
        }

        $path = $dir . '/' . $file;

        if (is_dir($path)) {
            listFiles($path, $depth + 1, $maxDepth);
        } else {
            echo $path . PHP_EOL;
        }
    }
}

// Usage
listFiles('/path/to/directory', 0, 5);