Yii2: Finding file and getting path in a directory tree

六月ゝ 毕业季﹏ 提交于 2019-12-10 22:04:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!