我有这段代码可以递归删除文件和目录。它工作正常,但有一个小问题。如果 $path = /var/www/foo/ 它将删除 foo 内部的所有内容,但不会删除 foo。我也想删除 foo 目录。任何想法?
public function delete($path) {
if(!file_exists($path)) {
throw new RecursiveDirectoryException('Directory doesn\'t exist.');
}
$directoryIterator = new DirectoryIterator($path);
foreach($directoryIterator as $fileInfo) {
$filePath = $fileInfo->getPathname();
if(!$fileInfo->isDot()) {
if($fileInfo->isFile()) {
unlink($filePath);
}
else if($fileInfo->isDir()) {
if($this->emptyDirectory($filePath)) {
rmdir($filePath);
}
else {
$this->delete($filePath);
rmdir($filePath);
}
}
}
}
}
为什么还要在你的函数中递归?
public function delete($path) {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
} elseif ($file->isDir()) {
rmdir($file->getPathname());
} elseif ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
}
}
rmdir($path);
}
它有效,因为RII::CHILD_FIRST
在父元素之前迭代子元素。因此,当它到达目录时,它应该是空的。
但实际的错误是由于您删除目录的位置造成的。在内部目录中,您可以在父迭代中执行此操作。这意味着您的根目录永远不会被删除。我建议在本地删除迭代中执行此操作:
public function delete($path) {
if(!file_exists($path)) {
throw new RecursiveDirectoryException('Directory doesn\'t exist.');
}
$directoryIterator = new DirectoryIterator($path);
foreach($directoryIterator as $fileInfo) {
$filePath = $fileInfo->getPathname();
if(!$fileInfo->isDot()) {
if($fileInfo->isFile()) {
unlink($filePath);
} elseif($fileInfo->isDir()) {
if($this->emptyDirectory($filePath)) {
rmdir($filePath);
} else {
$this->delete($filePath);
}
}
}
}
rmdir($path);
}
请注意这两个变化。我们只删除迭代内的空目录。呼唤$this->delete()
它将为您处理删除操作。第二个变化是增加了最后的rmdir
在该方法的最后...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)