php ZipArchive zip 压缩文件下载

347 阅读1分钟
<?php
/**
 * Created by.
 * User: Jim
 * Date: 2020/7/30
 * Time: 11:14
 */

namespace app\index\controller;


use app\index\services\SystemLogService;
use think\Controller;
use think\facade\Request;

class Index extends Controller
{

    protected $middleware = [];

    public function index()
    {
        //这里需要注意该目录是否存在,并且有创建的权限
        $zipname = 'test.zip';
        //这是要打包的文件地址数组
        $files = [
            'img/1.png',
            'img/2.png',
            'img/3.png',
            'img/4.png',
        ];
        $zip = new \ZipArchive();
        $res = $zip->open($zipname, \ZipArchive::CREATE);
        if ($res === TRUE) {
            foreach ($files as $file) {
                //这里直接用原文件的名字进行打包,也可以直接命名,需要注意如果文件名字一样会导致后面文件覆盖前面的文件,所以建议重新命名
//                $fileContent = file_get_contents($file);
//                $file = iconv('utf-8', 'GBK', basename($file));
//                $zip->addFromString($file, $fileContent);
                $zip->addFromString($file, $file);
            }
        }

        header('Content-Type: application/zip;charset=utf8');
        header('Content-disposition: attachment; filename=文件' . date('Y-m-d') . '.zip');
        header('Content-Length: ' . filesize($zipname));
        readfile($zipname);
        die;
    }
}