gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:11:48 24 4
gpt4 key购买 nike

我想获取所有子目录的列表并且我的以下代码有效,除非我对某些文件夹具有只读权限。

在下面的问题中,它显示了如何使用 RecursiveDirectoryIterator 跳过目录 Can I make RecursiveDirectoryIterator skip unreadable directories?但是我的代码在这里略有不同,我无法解决这个问题。

$path = 'www/';
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::KEY_AS_PATHNAME),
RecursiveIteratorIterator::CHILD_FIRST) as $file => $info)
{
if ($info->isDir())
{
echo $file . '<br>';
}
}

我得到了错误

Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(../../www/special): failed to open dir: Permission denied'

我已经尝试用其他问题中接受的答案替换它。

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

但是这段代码不会像我想要的那样给我一个 www 内所有目录的列表,我哪里出错了?

最佳答案

简介

您的代码的主要问题是使用 CHILD_FIRST

FROM PHP DOC

Optional mode. Possible values are

  • RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
  • RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
  • RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.

您应该使用SELF_FIRST 以便包含当前目录。您还忘记添加可选参数 RecursiveIteratorIterator::CATCH_GET_CHILD

FROM PHP DOC

Optional flag. Possible values are RecursiveIteratorIterator::CATCH_GET_CHILD which will then ignore exceptions thrown in calls to RecursiveIteratorIterator::getChildren().

重温您的代码

foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::KEY_AS_PATHNAME),
RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD) as $file => $info)
{
if ($info->isDir())
{
echo $file . '<br>';
}
}

你真的想要CHILD_FIRST

如果你真的想维护CHILD_FIRST结构那么我建议你使用ReadableDirectoryIterator

例子

foreach ( new RecursiveIteratorIterator(
new ReadableDirectoryIterator($path),RecursiveIteratorIterator::CHILD_FIRST) as $file ) {
echo $file . '<br>';
}

使用的类

class ReadableDirectoryIterator extends RecursiveFilterIterator {
function __construct($path) {
if (!$path instanceof RecursiveDirectoryIterator) {
if (! is_readable($path) || ! is_dir($path))
throw new InvalidArgumentException("$path is not a valid directory or not readable");
$path = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
}
parent::__construct($path);
}

public function accept() {
return $this->current()->isReadable() && $this->current()->isDir();
}
}

关于php - 无法使用 RecursiveDirectoryIterator 跳过不可读的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14410899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com