递归删除

tho*_*hom 4 php recursion unlink delete-file rmdir

我有这个代码来递归删除文件和目录.它工作正常,但有一点问题.如果$ 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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

irc*_*ell 12

为什么甚至会递归你的功能?

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);
}
Run Code Online (Sandbox Code Playgroud)

它有效,因为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);
}
Run Code Online (Sandbox Code Playgroud)

请注意这两个变化.我们只删除迭代内的空目录.调用$this->delete()它将为您处理删除.第二个变化是rmdir在方法结束时添加了决赛......