php - 我可以让 RecursiveDirectoryIterator 跳过不可读的目录吗?

标签 php directory directory-walk

foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".")) as $file) {
  echo "$file\n";
}

每当我尝试列出的目录中存在不可读的子目录时,是否有任何方法可以使此代码不抛出 UnexpectedValueException“无法打开目录:权限被拒绝”?

更新

foreach() 转换为 while() 并在 try() catch 中显式调用 Iterator::next() {} 没有帮助。这段代码:

$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
while($iter->valid()) {
    $file = $iter->current();
    echo "$file\n";
    try {
        $iter->next();
    } catch(UnexpectedValueException $e) {
    }
};

如果存在不可读的子目录,则为无限循环。

最佳答案

显然,您可以将 $flags 参数传递给构造函数。只有 one flag in the docs ,但它完全符合您的要求:在 getChildren() 调用期间捕获异常并简单地跳转到下一个元素

将您的类创建代码更改为

new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator("."), 
    RecursiveIteratorIterator::LEAVES_ONLY,
    RecursiveIteratorIterator::CATCH_GET_CHILD);

它应该可以工作

关于php - 我可以让 RecursiveDirectoryIterator 跳过不可读的目录吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4547485/

相关文章:

c# - 在 C# .Net 2.0 中使用文件属性

php - 我怎样才能制作一个按钮链接,就像在 Facebook 中一样?

php - 我只需要从另一个 html/php 页面导入表格

php - PDO errorInfo完整列表,特别是错误代码1451

maven-2 - 在maven中需要时创建目录

php - 无法使用 RecursiveDirectoryIterator 跳过不可读的目录

php - 如果在帖子中找到 .jpg .png 如何显示图像?

c# - Directory.SetAccessControl 设置不必要的权限

c - 使用 chdir() 是在 Linux C 中更改工作目录的唯一方法吗?

python - 遍历目录树的 Python 方法是什么?