php压缩文件并下载

本文将介绍如何使用PHP进行文件压缩,并允许用户下载压缩后的文件。我们将探讨相关函数的使用,包括读取文件、创建zip档案以及触发文件下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public function qrcode_export()
{
    $ids = input('ids');
    if (!$ids) {
        $this->error('数据异常');
    }
    $ids = explode(',', $ids);
    $word = Db::name('word');
    $word_data = $word->where('word_id', 'in', $ids)->select();
    $fileList = [];
    foreach ($word_data as $index => $word_datum) {
        $path = ROOT_PATH . 'Public/' . $word_datum['code_path'];
        if ($word_datum['code_path'] && file_exists($path)) {
            $img = $word_datum['code_path'];
        } else {
            $rr = request()->domain();
            $rr = $rr . url('student/home/code', ['wordId' => $word_datum['word_id']]);
            $name = $word_datum['grade_id'] . '_' . $word_datum['word_name'];
            $img = $this->qrcode($rr, $name);
            $word->where('word_id', $word_datum['word_id'])->update(['code_path' => $img]);

        }
        array_push($fileList, $img);
    }
    $this->zip_download($fileList, 'code');
}
public function zip_download($path, $filename)
{
    // 最终生成的文件名(含路径)
    $filename = ROOT_PATH . 'public/qrcode/' . $filename . '.zip';
    // 如果存在压缩文件,删除
    if (file_exists($filename)) {
        unlink($filename);
    }
    //重新生成文件
    $zip = new ZipArchive();
    if ($zip->open($filename, ZIPARCHIVE::CREATE) !== TRUE) {
        exit('无法打开文件,或者文件创建失败');
        return 0;
    }
    // 要压缩的文件
    $datalist = $path;
    // 遍历添加待压缩文件
    foreach ($datalist as $val) {
        $p = ROOT_PATH . 'Public/' . $val;
        if (file_exists($p)) {
            //val:qrcode/1_about.png
            $zip->addFile($val);
        }
    }
    // 关闭
    $zip->close();
    if (!file_exists($filename)) {
        // 即使创建,仍有可能失败
        exit('无法找到文件');
        return 0;
    }
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="qrcode_download.zip"');
    readfile($filename);
    return 1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值