What are some potential pitfalls when recursively reading directory structures in PHP?

One potential pitfall when recursively reading directory structures in PHP is the risk of encountering infinite loops if symbolic links or circular references are present. To solve this issue, you can keep track of the directories you have already visited and skip them if encountered again.

function readDirectory($dir, $visited = []) {
    if (in_array($dir, $visited)) {
        return;
    }
    
    $visited[] = $dir;
    
    $files = scandir($dir);
    
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $path = $dir . '/' . $file;
            
            if (is_dir($path)) {
                readDirectory($path, $visited);
            } else {
                echo $path . "\n";
            }
        }
    }
}

readDirectory('/path/to/directory');