php压缩多张图片并下载功能

本文介绍了一个使用PHP生成包含多张远程图片的压缩包的方法。该方法首先检查指定URL的图片是否可访问,然后将这些图片内容加入到一个ZIP压缩文件中,并提供下载。此过程涉及了文件操作、远程资源获取及HTTP头设置。

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

准备工作,使用phpinfo()查看有没有zip扩展

 

  1. <?php

  2. echo phpinfo();

 

/**
 * 下载图片并生成压缩包
 * @param $data    图片数组,一维
 * @param $tmpDir 存放路径
 * @return string
 */
public function downloadZipImg()
{
    $picAllArr = ['https://image.jewelryhunt.net/zhaowu/20220902/8ce8670a050ace3a10428b901d0698f9.jpg','https://image.jewelryhunt.net/zhaowu/20220902/6eb00d7855273840d3e4016002321973.jpg'];

    $tmpDir = 'download'; // 类似于/www/public/upload/

    if (!file_exists($tmpDir)) {
        //创建文件夹
        mkdir($tmpDir, 0777, true);
    }

    $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; // 压缩包文件名
    $zipNameUrl = $tmpDir . $zipName; // 文件路径

    // 生成文件
    $zip = new \ZipArchive();
    if ($zip->open($zipNameUrl,\ZipArchive::OVERWRITE) !== true) {
        //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
        if ($zip->open($zipNameUrl,\ZipArchive::CREATE) !== true) {
            // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
            return  '下载失败,文件夹不存在';
        }
    }

    foreach ($picAllArr as $file) {
        //判断图片是否存在
        $isFile = $this->checkFileExists($file);
        if (!$isFile) {
            continue;
        }
        //抓取图片内容
        $fileContent = file_get_contents($file);
        //添加图片
        $zip->addFromString(basename($file), $fileContent);
    }
    // 关闭
    $zip->close();

    //没有文件
    if (!file_exists($zipNameUrl)) {
        return '下载失败,图片不存在或无法下载';
    }

    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Content-disposition: attachment; filename=' . $zipName); //文件名
    header("Content-Type: application/zip"); //zip格式的
    header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
    header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器,文件大小

    // 下面2步必须要
    ob_clean();
    flush();

    @readfile($zipNameUrl);
    unlink($zipNameUrl); // 删除文件
    exit;
}

/**
 * 判断文件是否存在,支持本地及远程文件
 * @param String $file 文件路径
 * @return Boolean
 */
private function checkFileExists($file)
{
    // 远程文件
    if (strtolower(substr($file, 0, 5)) == 'https') {
        // 远程文件
        $header = get_headers($file, true);
        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));

    } elseif (strtolower(substr($file, 0, 4)) == 'http') {
        // 远程文件
        $header = get_headers($file, true);
        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
    } else {
        // 本地文件
        return file_exists($file);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值