PHP recursive directory path

前端 未结 2 1314
野性不改
野性不改 2020-11-27 21:39

i have this function to return the full directory tree:

function getDirectory( $path = \'.\', $level = 0 ){

$ignore = array( \'cgi-bin\', \'.\'         


        
相关标签:
2条回答
  • 2020-11-27 22:16

    Try to use RecursiveIteratorIterator in combination with RecursiveDirectoryIterator

    $path = realpath('/path/you/want/to/search/in');
    
    $objects = new RecursiveIteratorIterator(
                   new RecursiveDirectoryIterator($path), 
                   RecursiveIteratorIterator::SELF_FIRST);
    
    foreach($objects as $name => $object){
        if($object->getFilename() === 'work.txt') {
            echo $object->getPathname();
        }
    }
    

    Additional reading:

    • http://www.phpro.org/tutorials/Introduction-to-SPL.html
    0 讨论(0)
  • 2020-11-27 22:32

    do you have such a function or can you give me some tips on how to do this?

    Yes I do.

    I actually asked a similar question earlier this morning, but I figure it out. The problem I was having is that the file names . and .. are returned by readdir() and they cause problems when attempting to opendir() with them. When I filtered these out, my recursion worked perfectly. You might want to modify the format in which it outputs the directories that fit the search. Or modify it to output all files and directories. Find an image for "go.jpg" and try it out.

    I can't find my post to notify that I found the solution.

    define ('HOME', $_SERVER['DOCUMENT_ROOT']); 
    
       function searchalldirectories($directory, $seachterm, $maxrecursions, $maxopendir){
            $dircontent= '';
            $dirs= array();
            if ($maxopendir > 0){
                $maxopendir--;
                $handle= opendir( HOME.'/'.$directory);
                while (( $dirlisting= readdir($handle)) !== false){
                    $dn= ''; $fn= '  File';
                    if ( is_dir( HOME.'/'.$directory.'/'.$dirlisting) && $maxrecursions>0 && strpos( $dirlisting, '.')!==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:/'.$directory.'/'.$dirlisting.'"> '.$fn.':// <b>'.$directory.'/'.$dirlisting.$dn.'/</b><br>';
                    }
                }
                closedir( $handle);
                for ( $i=0; $i<count( $dirs); $i++){
                    $dircontent.= searchalldirectories( $dirs[$i], $seachterm, ($maxrecursions-1), $maxopendir);
                }
            }
            return $dircontent;
        }
    
    0 讨论(0)
提交回复
热议问题