3

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?

Antonio López
  • 386
  • 6
  • 22
  • Have a look into the documentation. The second argument controls what [findFiles](http://www.yiiframework.com/doc-2.0/yii-helpers-basefilehelper.html#findFiles%28%29-detail) will return (which file paths the returned array will contain). You have different options. – robsch Apr 14 '15 at 14:47

2 Answers2

3

You should simply try:

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

Read more here.

arogachev
  • 33,150
  • 7
  • 114
  • 117
soju
  • 25,111
  • 3
  • 68
  • 70
1

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());
    }
}
cetver
  • 11,279
  • 5
  • 36
  • 56