【问题标题】:PHP recursive file& folder delete function: 'Directory not empty' error messagePHP递归文件和文件夹删除功能:“目录不为空”错误消息
【发布时间】:2011-10-07 09:43:54
【问题描述】:

我正在尝试创建删除虚拟主机上的所有文件和目录的函数,不包括给定的文件和文件夹数组

function cleanUp($exdirs, $exfiles){
$it = new RecursiveIteratorIterator(
  new RecursiveDirectoryIterator('.'), 
  RecursiveIteratorIterator::CHILD_FIRST
);
foreach($it as $entry) {
  if ($entry->isDir() && !in_array($entry->getBasename(), $exdirs)) {
    rmdir($entry->getPathname());
  }
  else {
    if (!in_array($entry->getFileName(), $exfiles)) {
      unlink($entry->getPathname());
    }
    else {
      $exdirs[] = dirname($entry->getFileName());
    }
  }
}
}

然后像这样调用这个函数

$excludeDirsNames = array('cgi-bin');
$excludeFileNames = array('.htaccess', 'ws.zip', 'update.php');
cleanUp($excludeDirsNames , $excludeFileNames);

现在的问题是,它删除但收到错误消息:Directory not empty on line rmdir($entry->getPathname()); 几次。如何解决这个问题?

【问题讨论】:

  • 这不在这里吗:stackoverflow.com/questions/7685134/…。当您遇到上一个答案的问题时,我建议您返回该线程,取消选择您批准的答案并在那里提问。如果您选择的答案不起作用,您应该恢复您的选择,以免混淆未来的用户如何看待该主题。
  • 他给了我基本的想法。我无法取消选择
  • 我的意思是我不想取消选择。他给了我主要的想法

标签: php recursion rmdir


【解决方案1】:

您允许排除文件和目录,但您不测试目录是否包含之前排除的其他文件或目录。

if (substr($oneExcludedFileOrDirectory, 0, strlen($currentDir) === $currentDir) {
  echo "Directory not empty";
}

只是一个简单的前缀比较:“dir”是排除路径之一的前缀吗?仅适用于绝对路径(以及其他一些小事情),但它应该解释,这是怎么回事。

【讨论】:

  • 不明白。在我的功能中你的理论看起来如何
  • /path/to/my/file/path/to开头,那么/path/to/my/file就是in/path/to/,当你不删除/path/to/my/file时,那么/path/to就是不为空。
  • 更好?现在您应该可以自己将其集成到您的代码中了。
  • 它需要在foreach循环中?
  • 我真的无法将它集成到我的代码中。请告诉我它必须在哪里
【解决方案2】:

以下是它不起作用的两个原因:

1) 在您的一个子文件夹中是您要排除的文件。没有删除,所以无法“rm”文件夹。

2) 在“unlink”和“rmdir”-Funktion 之后调用“clearstatcache();”。我认为这将解决您的问题。文件已删除,但缓存中的信息仍然可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多