小编tho*_*hom的帖子

递归删除

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

php recursion unlink delete-file rmdir

4
推荐指数
1
解决办法
6539
查看次数

标签 统计

delete-file ×1

php ×1

recursion ×1

rmdir ×1

unlink ×1