Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP recursive directory path

i have this function to return the full directory tree:

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

$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.

$dh = @opendir( $path );
// Open the directory to the handle $dh

while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory

    if( !in_array( $file, $ignore ) ){
    // Check that this file is not to be ignored

        $spaces = str_repeat( ' ', ( $level * 4 ) );
        // Just to add spacing to the list, to better
        // show the directory tree.

        if( is_dir( "$path/$file" ) ){
        // Its a directory, so we need to keep reading down...

            echo "<strong>$spaces $file</strong><br />";
            getDirectory( "$path/$file", ($level+1) );
            // Re-call this same function but on a new directory.
            // this is what makes function recursive.

        } else {

            echo "$spaces $file<br />";
            // Just print out the filename

        }

    }

}

closedir( $dh );
// Close the directory handle

}

but what i want to do is to search for a file/folder and return it's path, how can i do that? do you have such a function or can you give me some tips on how to do this?

like image 989
kmunky Avatar asked Mar 07 '10 21:03

kmunky


People also ask

How can I get directory file in PHP?

The scandir() function returns an array of files and directories of the specified directory.

What is RecursiveDirectoryIterator?

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

What is Recursive directory Iterator?

The RecursiveDirectoryIterator class is used to enumerate all files in a directory and its subdirectories. RecursiveDirectoryIterator has some limitations: only forward iteration (++) is supported.


1 Answers

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
like image 62
Gordon Avatar answered Sep 29 '22 06:09

Gordon