What are some potential pitfalls to be aware of when using recursion in PHP to search through folders?

One potential pitfall when using recursion in PHP to search through folders is the risk of running into infinite loops if the recursion is not properly controlled. To avoid this, it is important to keep track of the folders that have already been visited to prevent revisiting them. One way to do this is by maintaining a list of visited folders and checking against it before recursing into a new folder.

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

// Usage
searchFolders('/path/to/folder');