What potential issues can arise when using a recursive script to display directory trees in PHP?
One potential issue that can arise when using a recursive script to display directory trees in PHP is infinite recursion, where the script gets stuck in an endless loop. This can happen if the script encounters a symbolic link or a circular reference within the directory structure. To solve this issue, you can keep track of visited directories and prevent revisiting them to break the recursion loop.
function displayDirectoryTree($dir, $level = 0, $visited = array()) {
if (in_array($dir, $visited)) {
return; // Prevent infinite recursion by checking if directory has been visited
}
$visited[] = $dir; // Mark current directory as visited
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
echo str_repeat(' ', $level) . $file . PHP_EOL;
if (is_dir($dir . '/' . $file)) {
displayDirectoryTree($dir . '/' . $file, $level + 1, $visited);
}
}
}
}
// Usage
displayDirectoryTree('/path/to/directory');