How can recursive functions be utilized to avoid getting stuck in infinite loops when scanning directories in PHP?

When scanning directories recursively in PHP, it's important to keep track of the directories already visited to avoid getting stuck in infinite loops. One way to do this is by using an array to store the paths of directories that have been scanned. Before scanning a new directory, check if it has already been visited to prevent revisiting it.

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

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