PHP实现文件压缩打包下载

  public function downZip($imgArr, $zipName)
    {
        //设置脚本的最大执行时间,设置为0则无时间限制
        set_time_limit(0);
        $name = iconv('utf-8', 'GBK', $zipName);
        ini_set('max_execution_time', '0');
        $filePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/zip';
        if (!is_dir($filePath)){
            mkdir($filePath,0777,true);
        }
        $filename = $filePath . '/' . $name . '.zip';
        $downName = $name . '.zip';
        $zip = new ipArchive();
        if ($zip->open($filename, IPARCHIVE::CREATE) !== TRUE) {
            exit('无法打开文件,或者文件创建失败');
            return 0;
        }
        foreach ($imgArr as $key => $val) {
            $res = @file_get_contents($val);
            if (empty($res))
            {
                continue;
            }
            $zip->addFromString($zipName.'_'.$key . '.jpg', $res);
        }
        $zip->close();
        $fp = fopen($filename, "r");
        $file_size = filesize($filename);//获取文件的字节

        header("Content-type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length:" . $file_size);
        header("Content-Disposition: attachment; filename=$downName");
        $buffer = 1024; //设置一次读取的字节数,每读取一次,就输出数据(即返回给浏览器)
        $file_count = 0; //读取的总字节数
        while (!feof($fp) && $file_count < $file_size) {
            $file_con = fread($fp, $buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);
    }

 

你可能感兴趣的