问题描述
foreach(新的RecursiveIteratorIterator(新的RecursiveDirectoryIterator(。))为$ file){echo$ file\\\
;
}
有没有办法这个代码不会抛出UnexpectedValueException无法打开目录:允许被拒绝每当目录中有一个不可读的子目录,我试图列出?
更新
将 foreach()
转换为 while()
并显式调用 Iterator: try()catch {}
没有帮助,包含在中的next()
这个代码:
$ iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(。));
while($ iter-> valid()){
$ file = $ iter-> current();
echo$ file\\\
;
try {
$ iter-> next();
} catch(UnexpectedValueException $ e){
}
};
如果有不可读子目录,则是无限循环。
显然,您可以将 $ flags
参数传递给构造函数。只有,但它做你想要的:捕获getChildren()调用中的异常,只需跳转到下一个元素
。
更改您的类创建代码
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(。),
RecursiveIteratorIterator: :LEAVES_ONLY,
RecursiveIteratorIterator :: CATCH_GET_CHILD);
它应该工作
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".")) as $file) {
echo "$file\n";
}
Is there any way for this code to not throw UnexpectedValueException "failed to open dir: Permission denied" whenever there is a unreadable subdirectory inside directory I attempt to list?
UPDATE
Converting foreach()
to while()
and explicitly calling Iterator::next()
wrapped in try() catch {}
doesn't help. This code:
$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
while($iter->valid()) {
$file = $iter->current();
echo "$file\n";
try {
$iter->next();
} catch(UnexpectedValueException $e) {
}
};
is an infinite loop if there is unreadable subdirectory.
Apparently you can pass $flags
parameter to constructor. There's only one flag in the docs, but it does exactly what you want: catches exceptions during getChildren() calls and simply jumps to the next element
.
Change your class creation code to
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("."),
RecursiveIteratorIterator::LEAVES_ONLY,
RecursiveIteratorIterator::CATCH_GET_CHILD);
and it should work
这篇关于可以让RecursiveDirectoryIterator跳过不可读目录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!