PHP在线压缩文件夹并下载

使用环境为php7.3

 

复制代码
     function createZip($openFile,$zipObj,$sourceAbso,$newRelat = '')
        {
            while(($file = readdir($openFile)) != false)
            {
                if($file=="." || $file=="..")
                    continue;

                /*源目录路径(绝对路径)*/
                $sourceTemp = $sourceAbso.'/'.$file;
                /*目标目录路径(相对路径)*/
                $newTemp = $newRelat==''?$file:$newRelat.'/'.$file;
                if(is_dir($sourceTemp))
                {
                    //echo '创建'.$newTemp.'文件夹<br/>';
                    $zipObj->addEmptyDir($newTemp);/*这里注意:php只需传递一个文件夹名称路径即可*/
                    createZip(opendir($sourceTemp),$zipObj,$sourceTemp,$newTemp);
                }
                if(is_file($sourceTemp))
                {
                    //echo '创建'.$newTemp.'文件<br/>';
                    $zipObj->addFile($sourceTemp,$newTemp);
                }
            }
        }


//创建<span style="font-family: Arial, Helvetica, sans-serif;">ZipArchive对象</span>
        $exportPath= $_SERVER['DOCUMENT_ROOT'].'/json';
        $filename=$exportPath.'.zip';
        $zip = new \ZipArchive();
//参数1:zip保存路径,参数2:ZIPARCHIVE::CREATE没有即是创建
        if(!$zip->open($filename,\ZIPARCHIVE::CREATE))
        {
            echo "创建[exportPath.zip]失败<br/>";return;
        }
//echo "创建[$exportPath.zip]成功<br/>";
        createZip(opendir($exportPath),$zip,$exportPath);
        $zip->close();

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

 

posted @   赵瑛  阅读(368)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战

版权所有 © 2022 沅来是澧

如果有程序开发、网站建设等需求的请联系我,QQ:47419233

点击右上角即可分享
微信分享提示