PHP扩展类ZipArchive实现压缩Zip文件和文件打包下载
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP扩展类ZipArchive实现压缩Zip文件和文件打包下载,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2355字,纯文字阅读大概需要4分钟。
内容图文
1 <?php
2/**
3 * 关于文件压缩和下载的类
4 * @author tycell
5 * @version 1.0
6*/ 7class zip_down{
8 9protected$file_path;
10/**
11 * 构造函数
12 * @param [string] $path [传入文件目录]
13*/14publicfunction __construct($path){
15$this->file_path=$path; //要打包的根目录16 }
17/**
18 * 入口调用函数
19 * @return [type] [以二进制流的形式返回给浏览器下载到本地]
20*/21publicfunction index(){
22$zip=new ZipArchive();
23$end_dir=$this->file_path.date(‘Ymd‘,time()).‘.zip‘;//定义打包后的包名24$dir=$this->file_path;
25if(!is_dir($dir)){
26mkdir($dir);
27 }
28if($zip->open($end_dir, ZipArchive::OVERWRITE) === TRUE){ ///ZipArchive::OVERWRITE 如果文件存在则覆盖29$this->addFileToZip($dir, $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法30$zip->close();
31 }
32if(!file_exists($end_dir)){
33exit("无法找到文件");
34 }
35header("Cache-Control: public");
36header("Content-Description: File Transfer");
37header("Content-Type: application/zip"); //zip格式的 38header(‘Content-disposition: attachment; filename=‘.basename($end_dir)); //文件名 39header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件 40header(‘Content-Length:‘.filesize($end_dir)); //告诉浏览器,文件大小 41 @readfile($end_dir);
42$this->delDirAndFile($dir,true);//删除目录和文件43unlink($end_dir);////删除压缩包44 }
45/**
46 * 文件压缩函数 需要开启php zip扩展
47 * @param [string] $path [路径]
48 * @param [object] $zip [扩展ZipArchive类对象]
49*/50protectedfunction addFileToZip($path, $zip){
51$handler = opendir($path);
52while (($filename=readdir($handler)) !== false) {
53if ($filename!= "." && $filename!=".."){
54if(is_dir($path."/".$filename)){
55$this->addFileToZip($path."/".$filename,$zip);
56 } else {
57$zip->addFile($path."/".$filename);
58 }
59 }
60 }
61 @closedir($path);
62 }
63/**
64 * 删除文件函数
65 * @param [string] $dir [文件目录]
66 * @param boolean $delDir [是否删除目录]
67 * @return [type] [description]
68*/69protectedfunction delDirAndFile($path,$delDir=true){
70$handle=opendir($path);
71if($handle){
72while(false!==($item = readdir($handle))){
73if($item!="."&&$item!=".."){
74if(is_dir($path.‘/‘.$item)){
75$this->delDirAndFile($path.‘/‘.$item, $delDir);
76 }else{
77unlink($path.‘/‘.$item);
78 }
79 }
80 }
81 @closedir($handle);
82if($delDir){returnrmdir($path);}
83 }else{
84if(file_exists($path)){
85returnunlink($path);
86 }else{
87returnFALSE;
88 }
89 }
90 }
9192 }
原文:http://www.cnblogs.com/wumoran/p/6764386.html
内容总结
以上是互联网集市为您收集整理的PHP扩展类ZipArchive实现压缩Zip文件和文件打包下载全部内容,希望文章能够帮你解决PHP扩展类ZipArchive实现压缩Zip文件和文件打包下载所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。