php框架tp6自学笔记——压缩文件下载

压缩文件

  • 我压缩的文件里有三个文件夹,在每个文件夹下又包含了很多文件
  • 压缩后直接下载下来了,项目文件里的压缩包被直接删除、
  • 需要引入use think\ZipArchive;
        $dir = './stateProposal';
        $zipName = "./AllStateProposal.zip";
        // 如果压缩文件不存在,就创建压缩文件
        if (!is_file($zipName)) {
            $fp = fopen($zipName, 'w');
            fclose($fp);
        }
        $zip = new \ZipArchive();
        // OVERWRITE选项表示每次压缩时都覆盖原有内容,但是如果没有那个压缩文件的话就会报错,所以事先要创建好压缩文件
        // 也可以使用CREATE选项,此选项表示每次压缩时都是追加,不是覆盖,如果事先压缩文件不存在会自动创建
        if ($zip->open($zipName, \ZipArchive::OVERWRITE) === true) {
            $this->addFileToZip($dir, $zip);//压缩目录下的各个文件,这个函数是自己写的,要加在自己的php文件中
            $zip->close();

            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");

            header("Content-Length: " . filesize($zipName));
            header("Content-Disposition: attachment; filename=\"" . basename($zipName) . "\"");
            ob_clean(); flush();
            readfile($zipName);
            unlink($zipName);//完成所有操作 删除压缩包
        } else {
            exit('下载失败!');
        }

    public function addFileToZip($path,$zip){
        $handler=opendir($path); //打开当前文件夹由$path指定。
        while(($filename=readdir($handler))!==false){
            if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’,不要对他们进行操作
                if(is_dir($path."/".$filename)){
                    $this->addFileToZip($path."/".$filename, $zip);
                }else{
                    $zip->addFile($path."/".$filename);
                }
            }
        }
        @closedir($path);
    }

你可能感兴趣的:(php)