• PHP下载压缩包文件


    压缩文件

     1 $zip = new ZipArchive();
     2 // 打开一个zip文档,ZipArchive::OVERWRITE:如果存在这样的文档,则覆盖;ZipArchive::CREATE:如果不存在,则创建
     3 $res = $zip->open('test.zip', ZipArchive::OVERWRITE | ZipArchive::CREATE);
     4 if($res)
     5 {
     6     // 添加 a.txt 到压缩文档
     7     $zip->addFile('a.txt');
     8     // 添加一个字符串到压缩文档中的b.txt
     9     $zip->addFromString('b.txt', 'this is b.txt');
    10     // 添加一个空目录b到压缩文档
    11     $zip->addEmptyDir('b');
    12 }
    13 // 关闭打开的压缩文档
    14 $zip->close();

    压缩目录

     1  1 /**
     2  2  * @param $dir 目标目录路径
     3  3  * @param $zip ZipArchive类对象
     4  4  * @param $prev
     5  5  */
     6  6 function compressDir($dir, $zip, $prev='.')
     7  7 {
     8  8     $handler = opendir($dir);
     9  9     $basename = basename($dir);
    10 10     $zip->addEmptyDir($prev . '/' . $basename);
    11 11     while($file = readdir($handler))
    12 12     {
    13 13         $realpath = $dir . '/' . $file;
    14 14         if(is_dir($realpath))
    15 15         {
    16 16             if($file !== '.' && $file !== '..')
    17 17             {
    18 18                 $zip->addEmptyDir($prev . '/' . $basename . '/' . $file);
    19 19                 compressDir($realpath, $zip, $prev . '/' . $basename);
    20 20             }
    21 21         }else
    22 22         {
    23 23             $zip->addFile($realpath, $prev. '/' . $basename . '/' . $file);
    24 24         }
    25 25     }
    26 26 
    27 27     closedir($handler);
    28 28     return null;
    29 29 }
    30 30 
    31 31 $zip = new ZipArchive();
    32 32 $res = $zip->open('test.zip', ZipArchive::OVERWRITE | ZipArchive::CREATE);
    33 33 if($res)
    34 34 {
    35 35     compressDir('./test', $zip);
    36 36     $zip->close();
    37 37 }

    解压缩

    1 $zip = new ZipArchive();
    2 $res = $zip->open('test1.zip');
    3 if($res)
    4 {
    5     // 解压缩文件到指定目录
    6     $zip->extractTo('test');
    7     $zip->close();
    8 }

    下载压缩包

    1 header('Content-Type:text/html;charset=utf-8');
    2 header('Content-disposition:attachment;filename=test.zip');
    3 $filesize = filesize('./test.zip');
    4 readfile('./test.zip');
    5 header('Content-length:'.$filesize);
    6 
    7 unlink('./test.zip');
  • 相关阅读:
    c语言指针应用总结
    C语言指针知识点
    标准输出scanf函数
    C语言32个关键字查询
    kali2020 无法使用arpspoof ,切换阿里云源进行安装
    “中国网络安全能力图谱”发布,安华金和当选数据安全领域代表者!
    【官方文档】-Windows Server 安装和升级
    SQL Server 2012配置Always On可用性组
    【官方文档】-SQL Server 的最大容量规范
    【官方文档】-按 SQL Server 版本划分的计算能力限制
  • 原文地址:https://www.cnblogs.com/zgxblog/p/10132958.html
Copyright © 2020-2023  润新知