简体   繁体   中英

Recursive Search of Directories php

Wow, StackOverFlow does a great job even AJAX search of topics and answered questions as I type in the title. Truly worthy programmers.

The code follows. It works just fine, when I set max recursion to 0. So it seems obvious that the problem is in my recursion code. But i can't find it.

I considered that opendir might return a handle that is global and I was stepping on it in the next recursion, so I set the recursion outside the opendir handle. No recursion is called with a handle open and it still produces nothing when max recursion is more than zero. I even added a max opened dir. As you see that variable pass down through the recursions, it will not opendir if $maxopendir is zero. If that were the problem, I would still get something back. But I get nothing, unless of course $maxrecursions is 0, then its fine and returns all files or directory names in HOME directory that match the search term.

Any experts on recursion that can correct me?

$dircontent.= searchalldirectories(HOME, $_POST['search'], 0, 5);

function searchalldirectories($directory, $seachterm, $maxrecursions, $maxopendir){
    $dircontent= '';
    $dirs= array();
    if ($maxopendir>0){
        $maxopendir--;
        $handle= opendir($directory);
        while (($dirlisting= readdir($handle))!==false){
            $dn= ''; $fn= '  File';
            if (is_dir($directory.'/'.$dirlisting) && $maxrecursions>0){
                $dirs[count($dirs)]= $directory.'/'.$dirlisting;
                $dn= '/'; $fn= 'Dir';
            }                           
            if (stripos($dirlisting, $seachterm)!==false){
                $dircontent.= '<input type="image" src="go.jpg" name="cmd" value="home:/'.$dirlisting.'"> '.$fn.':// <b>'.$dirlisting.$dn.'/</b><br>';
            }
        }
        closedir($handle);
        for ($i=0; $i<count($dirs); $i++){
            $dircontent.= searchalldirectories($dirs[$i], $s, ($maxrecursions-1), $maxopendir);
        }
    }
    return $dircontent;
}

Your loop appears to be running away with itself when the opendir fails. You may try testing the return value like so:

if(!($handle= opendir($directory))) {
        echo "Could not opendir($directory)\n";
        return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM