tags:

views:

134

answers:

2

I tried to write a script to list all files in directories and subdirectories and so on.. The script works fine if I don't include the check to see whether any of the files are directories. The code doesn't generate errors but it generates a hundred lines of text saying "Directory Listing of ." instead of what I was expecting. Any idea why this isn't working?

<?php

//define the path as relative
$path = "./";

function listagain($pth)
{
//using the opendir function
$dir_handle = @opendir($pth) or die("Unable to open $pth");

echo "Directory Listing of $pth<br/>";

//running the while loop
while ($file = readdir($dir_handle)) 
{
    //check whether file is directory
    if(is_dir($file))
    {
     //if it is, generate it's list of files
     listagain($file);
    }
    else
    {
     if($file!="." && $file!="..")
     echo "<a href='$file'>$file</a><br/>";
    }
}
//closing the directory
closedir($dir_handle);
}

listagain($path)

?>
+1  A: 

The problem is, variable $file contains only basename of path. So, you need to use $pth.$file.

+4  A: 

The first enties . and .. refer to the current and parent directory respectivly. So you get a infinite recursion.

You should first check for that before checking the file type:

if ($file!="." && $file!="..") {
    if (is_dir($file)) {
        listagain($file);
    } else {
        echo '<a href="'.htmlspecialchars($file).'">'.htmlspecialchars($file).'</a><br/>';
    }
}
Gumbo