Jump to content

Where's the endless loop here?


Dudemanguy

Recommended Posts

The function here is supposed to catalog the files in a given folder, and all subfolders, and report back the filenames to the screen as links to themselves. Despite my best amateur efforts, I can't get away from the endless loop errors.

 

function explore($dir, $filePath)
{	$blah = opendir($dir);
while (false !== ($file = readdir($blah)))
{if (is_dir($file))
    {
	$filePath = $filePath.$file.'\\';
	closedir($blah);
	 explore($file, $filePath);}
 else
 	{
 	$filePath = $filePath.$file;
 	 echo "<a href='$filePath'>'$file'</a>";
 	 echo "<br />";}
 	 $fLength = strlen($file);
 	 $fpLength = strlen($filePath);
 	 $filePath = substr($filePath, 0, ($fpLength -$fLength));
}
}

Link to comment
https://forums.phpfreaks.com/topic/230041-wheres-the-endless-loop-here/
Share on other sites

Hmm, I think that readdir returns just the file name, not the full path. Try the below code (completely untested). You should pass in a complete path ending with a /.

 

function explore($dir)
{	$blah = opendir($dir);
while (false !== ($file = readdir($blah)))
{if (is_dir($dir.$file))
    {
	 explore($dir.$file.'/');}
 else
 	{
 	$filePath = $dir.$file;
 	 echo "<a href='$filePath'>'$file'</a>";
 	 echo "<br />";}
}
closedir($blah);
}

The readdir returns the filename, and which I construct manually into a path with "$filePath = $filePath.$file.'\\';" although this is the area that I get the most errors. With your code, I got a different error, but with a similar source.

 

I usually get this:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 21515 bytes) in C:\Xampp\xampp\www\htdocs\list.php on line 21

 

Line 21 for me is:

$filePath = $filePath.$file.'\\';

Your problem is that two of the "folders" returned in a directory are '.' and '..'. Which attempt to traverse the directory tree upwards. You need to exclude those fromthe recursive call. Your function is also overly-complicated. You also shouldn't close the filehandle in the loop/. Otherwise once the first subdirectory is run the process will fail ont he next object in the root directory.

 

function explore($dir)
{
    $handle = opendir($dir);
while (false !== ($file = readdir($handle)))
{
        $fullPath = $dir.DIRECTORY_SEPARATOR.$file;
        if (is_dir($file))
    {
            if($file!='.' && $file!='..')
            {
                explore($fullPath);
            }
        }
        else
        {
            echo "<a href=\"$fullPath\">$file</a><br />\n";
        }
    }
    closedir($handle);
}

  • 2 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.