Yii2: Finding file and getting path in a directory tree

3.7k Views Asked by At

I'm trying to search for a single filename in a bunch of directories and returning its path. I thought FileHelper::findFiles() would be a helping hand but it seems it doesn't accept a filename to search for but just a particular root directory and then it returns an array of found filenames.

Anyone who knows another Yii2 helper to accomplish this?

2

There are 2 best solutions below

1
soju On BEST ANSWER

You should simply try:

$files = yii\helpers\FileHelper::findFiles('/path', [
    'only' => ['filename.ext'],
    'recursive' => true,
]);

Read more here.

0
cetver On

You can do it easy on "pure" PHP

/**
 * @var $file SplFileInfo
 */
$path = '/path';
$dirIter = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dirIter, RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file) {
    if ($file->isFile() === true && $file->getFilename() === '.htaccess') {
        var_dump($file->getPathname());
    }
}