问题
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?
回答1:
You should simply try:
$files = yii\helpers\FileHelper::findFiles('/path', [
'only' => ['filename.ext'],
'recursive' => true,
]);
Read more here.
回答2:
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());
}
}
来源:https://stackoverflow.com/questions/29629221/yii2-finding-file-and-getting-path-in-a-directory-tree