PHP рекурсивный путь к каталогу

у меня есть эта функция для возврата 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

}

но то, что я хочу сделать, должно искать файл/папку и возврат, это - путь, как я могу сделать это? у Вас есть такая функция, или можно ли дать мне некоторые подсказки относительно того, как сделать это?

8
задан kmunky 7 March 2010 в 21:57
поделиться

1 ответ

Попробуйте использовать RecursiveIteratorIterator в сочетании с 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();
    }
}

Дополнительное чтение:

21
ответ дан 5 December 2019 в 07:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: