当前位置: 首页 > 编程文章 >

PHP实现多文件压缩为ZIP并下载的方法

PHP实现多文件压缩为ZIP并下载的方法

作者:沈宁时间:2025-10-07 09:35:20浏览:117

本文介绍利用PHP的ZipArchive类将多个指定文件打包成ZIP格式,并通过HTTP头信息触发浏览器下载的功能。核心步骤包括初始化压缩包、遍历文件列表添加内容、关闭资源以及设置正确的Content-Type和Content-Disposition响应头以实现附件下载。

本文目录收起

PHP多文件压缩与下载实现

本示例展示了如何使用PHP将多个文件整合压缩为ZIP格式,并支持直接下载到本地环境。以下内容供开发者参考与实践。

以下直接提供核心实现代码。


//这里需要注意该目录是否存在,并且有创建的权限
$zipname = 'path/test.zip'
//这是要打包的文件地址数组
$files = array("mypath/test1.txt","mypath/test2.pdf");
$zip = new ZipArchive();
$res = $zip->open($zipname, ZipArchive::CREATE);
if ($res === TRUE) {
 foreach ($files as $file) {
 //这里直接用原文件的名字进行打包,也可以直接命名,需要注意如果文件名字一样会导致后面文件覆盖前面的文件,所以建议重新命名
  $new_filename = substr($file, strrpos($file, '/') + 1);
  $zip->addFile($file, $new_filename);
 }
}
//关闭文件
$zip->close();


//这里是下载zip文件
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: " . filesize($zipname));
header("Content-Disposition: attachment; filename=\"" . basename($zipname) . "\"");
readfile($zipname);
exit;

此外,还提供一个封装好的ZIP压缩类供选用。


<?php
# 
# PHPZip v1.2 by Sext (sext@neud.net) 2002-11-18
#   (Changed: 2003-03-01)
# 
# Makes zip archive
#
# Based on "Zip file creation class", uses zLib
#
#
class PHPZip
{
  function Zip($dir, $zipfilename)
  {
    if (@function_exists('gzcompress'))
    {  
      $curdir = getcwd();
      if (is_array($dir)) 
      {
          $filelist = $dir;
      }
      else 
      {
        $filelist = $this -> GetFileList($dir);
      }
      if ((!empty($dir))&&(!is_array($dir))&&(file_exists($dir))) chdir($dir);
      else chdir($curdir);
      if (count($filelist)>0)
      {
        foreach($filelist as $filename)
        {
          if (is_file($filename))
          {
            $fd = fopen ($filename, "r");
            $content = fread ($fd, filesize ($filename));
            fclose ($fd);
            if (is_array($dir)) $filename = basename($filename);
            $this -> addFile($content, $filename);
          }
        }
        $out = $this -> file();
        chdir($curdir);
        $fp = fopen($zipfilename, "w");
        fwrite($fp, $out, strlen($out));
        fclose($fp);
      }
      return 1;
    } 
    else return 0;
  }
  function GetFileList($dir)
  {
    if (file_exists($dir))
    {
      $args = func_get_args();
      $pref = $args[1];
      $dh = opendir($dir);
      while($files = readdir($dh))
      {
        if (($files!=".")&&($files!="..")) 
        {
          if (is_dir($dir.$files)) 
          {
            $curdir = getcwd();
            chdir($dir.$files);
            $file = array_merge($file, $this -> GetFileList("", "$pref$files/"));
            chdir($curdir);
          }
          else $file[]=$pref.$files;
        }
      }
      closedir($dh);
    }
    return $file;
  }
  var $datasec   = array();
  var $ctrl_dir   = array();
  var $eof_ctrl_dir = "x50x4bx05x06x00x00x00x00";
  var $old_offset  = 0;
  /**
   * Converts an Unix timestamp to a four byte DOS date and time format (date
   * in high two bytes, time in low two bytes allowing magnitude comparison).
   *
   * @param integer the current Unix timestamp
   *
   * @return integer the current date in a four byte DOS format
   *
   * @access private
   */
  function unix2DosTime($unixtime = 0) {
    $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
    if ($timearray['year'] < 1980) {
      $timearray['year']  = 1980;
      $timearray['mon']   = 1;
      $timearray['mday']  = 1;
      $timearray['hours']  = 0;
      $timearray['minutes'] = 0;
      $timearray['seconds'] = 0;
    } // end if
    return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
        ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
  } // end of the 'unix2DosTime()' method
  /**
   * Adds "file" to archive
   *
   * @param string  file contents
   * @param string  name of the file in the archive (may contains the path)
   * @param integer the current timestamp
   *
   * @access public
   */
  function addFile($data, $name, $time = 0)
  {
    $name   = str_replace('', '/', $name);
    $dtime  = dechex($this->unix2DosTime($time));
    $hexdtime = 'x' . $dtime[6] . $dtime[7]
         . 'x' . $dtime[4] . $dtime[5]
         . 'x' . $dtime[2] . $dtime[3]
         . 'x' . $dtime[0] . $dtime[1];
    eval('$hexdtime = "' . $hexdtime . '";');
    $fr  = "x50x4bx03x04";
    $fr  .= "x14x00";      // ver needed to extract
    $fr  .= "x00x00";      // gen purpose bit flag
    $fr  .= "x08x00";      // compression method
    $fr  .= $hexdtime;       // last mod time and date
    // "local file header" segment
    $unc_len = strlen($data);
    $crc   = crc32($data);
    $zdata  = gzcompress($data);
    $c_len  = strlen($zdata);
    $zdata  = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
    $fr   .= pack('V', $crc);       // crc32
    $fr   .= pack('V', $c_len);      // compressed filesize
    $fr   .= pack('V', $unc_len);     // uncompressed filesize
    $fr   .= pack('v', strlen($name));  // length of filename
    $fr   .= pack('v', 0);        // extra field length
    $fr   .= $name;
    // "file data" segment
    $fr .= $zdata;
    // "data descriptor" segment (optional but necessary if archive is not
    // served as file)
    $fr .= pack('V', $crc);         // crc32
    $fr .= pack('V', $c_len);        // compressed filesize
    $fr .= pack('V', $unc_len);       // uncompressed filesize
    // add this entry to array
    $this -> datasec[] = $fr;
    $new_offset    = strlen(implode('', $this->datasec));
    // now add to central directory record
    $cdrec = "x50x4bx01x02";
    $cdrec .= "x00x00";        // version made by
    $cdrec .= "x14x00";        // version needed to extract
    $cdrec .= "x00x00";        // gen purpose bit flag
    $cdrec .= "x08x00";        // compression method
    $cdrec .= $hexdtime;         // last mod time & date
    $cdrec .= pack('V', $crc);      // crc32
    $cdrec .= pack('V', $c_len);     // compressed filesize
    $cdrec .= pack('V', $unc_len);    // uncompressed filesize
    $cdrec .= pack('v', strlen($name) ); // length of filename
    $cdrec .= pack('v', 0 );       // extra field length
    $cdrec .= pack('v', 0 );       // file comment length
    $cdrec .= pack('v', 0 );       // disk number start
    $cdrec .= pack('v', 0 );       // internal file attributes
    $cdrec .= pack('V', 32 );      // external file attributes - 'archive' bit set
    $cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
    $this -> old_offset = $new_offset;
    $cdrec .= $name;
    // optional extra field, file comment goes here
    // save to central directory
    $this -> ctrl_dir[] = $cdrec;
  } // end of the 'addFile()' method
  /**
   * Dumps out file
   *
   * @return string the zipped file
   *
   * @access public
   */
  function file()
  {
    $data  = implode('', $this -> datasec);
    $ctrldir = implode('', $this -> ctrl_dir);
    return
      $data .
      $ctrldir .
      $this -> eof_ctrl_dir .
      pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk"
      pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall
      pack('V', strlen($ctrldir)) .      // size of central dir
      pack('V', strlen($data)) .       // offset to start of central dir
      "x00x00";               // .zip file comment length
  } // end of the 'file()' method
} // end of the 'PHPZip' class
?>

该类的使用方式如下:


$zipfiles =array("/root/pooy/test1.txt","/root/pooy/test2.txt");
$z = new PHPZip();
//$randomstr = random(8);
$zipfile = TEMP."/photocome_".$groupid.".zip";
$z->Zip($zipfiles, $zipfile);

希望上述内容能对您的PHP开发工作提供帮助。

上一篇
PHP定时自动生成静态HTML的实现代码

本文介绍在虚拟主机环境下,通过判断已生成文件时间与当前时间差值来触发静态页面生成的方法。核心利用 ob_start 开启输出缓冲,捕获动态内容后使用 file_put_contents 写入 HTML 文件,并兼容低版本 PHP 的自定义写入函数,实现简便的伪定时更新机制。

下一篇
PHP CURL与Java HTTP请求实现详解

本文介绍在PHP和Java中实现第三方平台数据交互的方法。PHP通过CURL扩展模拟浏览器发起GET或POST请求获取JSON数据,需在php.ini中开启配置;Java则利用HttpRequest类封装URL连接逻辑,结合Spring MVC框架在Controller中调用并解析响应结果,两者均用于解决敏感接口只能在特定服务器运行的跨平台调用需求。

相关文章

更多
PHP使用ZipArchive打包文件并分块下载的实现

本文介绍如何利用PHP内置的ZipArchive类将多个文件打包为ZIP格式,并通过设置HTTP响应头实现大文件的分块下载。核心在于使用fopen、fread和fclose配合缓冲区(Buffer)逐块读取文件内容,避免一次性加载导致内存溢出,同时通过Content-Disposition等Header控制浏览器的保存行为。

2026.05.10 807
PHP实现文件安全下载

通过PHP直接读取文件并输出,可防止用户直接复制URL访问资源。该方法先检查本地文件是否存在,随后设置Content-type为application/octet-stream及Content-Disposition为attachment,强制浏览器触发下载对话框而非预览。对于远程HTTP或FTP源,需调整打开方式并分块读取内容以确保稳定性。

2026.09.27 490
PHP实现打包zip并下载功能

本文介绍利用PHP的ZipArchive类实现动态打包文件并触发浏览器下载的方法。核心步骤包括创建或复制模板ZIP文件、添加目录与内容,以及通过循环读取文件流向客户端输出数据,确保下载过程稳定且临时文件被正确清理。

2026.06.15 312
PHP实现素材图片上传与ZIP打包下载功能详解

本文介绍基于PHP的素材图片上传与下载实现方案。上传环节利用move_uploaded_file函数存储文件并记录路径,需注意路径和文件名避免中文。下载环节依赖ZipArchive类生成ZIP包,Linux需开启zlib,Windows需启用php_zip.dll。通过设置请求头触发浏览器下载,并在传输完成后删除服务器端的临时ZIP文件,同时支持OSS等第三方存储场景外的本地文件处理。

2025.08.14 999
PHP实现流文件发送与接收的完整方案

本文介绍在PHP中通过流形式发送和接收文件的具体实现方法。主要包含两个核心脚本:sendStreamFile.php用于以流的方式输出文件,receiveStreamFile.php负责接收流数据并保存至本地。此外,还补充了利用fopen读取远程流文件并设置HTTP响应头的标准代码片段,适用于需要处理大文件或避免内存溢出的场景。

2026.03.19 997
解决PHP ZipArchive类未找到的Fatal Error方法

在使用PHP的ZipArchive类创建或解压ZIP文件时,若出现Fatal error: Class 'ZipArchive' not found错误,通常是因为PHP环境未启用zip扩展。Windows用户需在php.ini中移除extension=php_zip.dll前的分号并重启Apache;Linux用户需重新编译安装zip模块生成zip.so,并在php.ini中添加extension路径后重启服务。

2025.06.10 995

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。