将文件夹压缩成zip文件的php代码


Posted in PHP onDecember 14, 2009

1.请先下载我准备好的zip.php工具类,下载后解压,将里面的文件放入对应的目录中,我是放在虚拟目录下的include文件夹中。
2.在你的php文件中加入下面代码即可

require_once "./include/zip.php"; 
$zip = new PHPZip(); 
//$zip -> createZip("要压缩的文件夹目录地址", "压缩后的文件名.zip"); //只生成不自动下载 
$zip -> downloadZip("要压缩的文件夹目录地址", "压缩后的文件名.zip");
//自动下载

实例:可以参考下面的伪代码来看一个具体的使用场景:
代码
require_once "./include/zip.php"; 
if (!$download) { 
exit(); 
} 
set_time_limit(60); 
$tmpManager = new TmpManager(); //假设我们有一个类来完成后面的操作 
$tempfolder = array(); 
$tempfile = array(); 
//假设我们是通过在页面上选择checkbox来下载已选的文件夹或文件,并一同打包 
for($i = 0;$i < $checkboxnum;$i++) { 
$value = ${"select".$i}; 
if ($value != '') { 
$this_type = substr($value, 0, 1); 
$this_id = substr($value, 1); 
//将文件夹和文件的情况分开处理 
if ($this_type == 'd') { 
$tempfolder[] = $this_id; 
} 
elseif ($this_type == 'f') { 
$tempfile[] = $this_id; 
} 
} 
} 
@mkdir($tempdir); 
$curtempdir = "$tempdir/".$userid; //不同用户在不同的临时文件夹下操作 
if (file_exists($curtempdir)) { 
$tmpManager->DeleteDir($curtempdir); //删除旧的文件夹 
} 
if (sizeof($tempfolder) > 0 || sizeof($tempfile) > 0) { 
mkdir($curtempdir, 0777); //如果有要打包的文件货文件夹,重新创建文件夹 
} 
if (sizeof($tempfile) > 0) { 
$tmpManager->CopyFile($tempfile,$curtempdir); //将要下载的文件copy到创建的文件夹 
} 
if (sizeof($tempfolder) > 0) { 
$tmpManager->CopyFolder($tempfolder,$curtempdir); //将要下载的文件夹copy到创建的文件夹 
} 
$zip = new PHPZip(); 
$zip -> downloadZip($curtempdir, "file_".date('Ymd').".zip"); //打包并下载

zip.php
<?php 
/* 
    File name: /include/zip.php 
    Author:    Horace 2009/04/15 
*/ 
class PHPZip{ 
    var $dirInfo = array("0","0"); 
    var $rootDir = ''; 
    var $datasec = array(); 
    var $ctrl_dir = array(); 
    var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; 
    var $old_offset = 0;     function downloadZip(){ 
        createZip($dir, $zipfilename, true); 
    } 
    function createZip($dir, $zipfilename, $autoDownload = false){ 
        if (@function_exists('gzcompress')){ 
            @set_time_limit("0"); 
            if (is_array($dir)){ 
                $fd = fopen ($dir, "r"); 
                $fileValue = fread ($fd, filesize ($filename)); 
                fclose ($fd); 
                if (is_array($dir)) $filename = basename($dir); 
                $this -> addFile($fileValue, "$filename"); 
            }else{ 
                $this->dirTree($dir,$dir); 
            } 
            $zipfilenametemp = time().$zipfilename; 
            $out = $this -> filezip(); 
            $fp = fopen($zipfilenametemp, "w"); 
            fwrite($fp, $out, strlen($out)); 
            fclose($fp); 
            $filesize = filesize($zipfilenametemp); 
            if ($filesize < 104857600) { 
                if($autoDownload){ 
                    header("Content-type: application/octet-stream"); 
                    header("Content-disposition: attachment; filename=".$zipfilename); 
                } 
                echo $this -> filezip(); 
            }else{ 
                echo "create zip error!"; 
            } 
            unlink($zipfilenametemp); 
        } 
     } 
    //get dir tree.. 
    function dirTree($directory,$rootDir){ 
        global $_SERVER,$dirInfo,$rootDir; 
        $fileDir=$rootDir; 
        $myDir=dir($directory); 
        while($file=$myDir->read()){ 
            if(is_dir("$directory/$file") and $file!="." and $file!=".."){ 
                $dirInfo[0]++; 
                $rootDir ="$fileDir$file/"; 
                $this -> addFile('', "$rootDir"); 
                //go on n's folders 
                $this->dirTree("$directory/$file",$rootDir); 
            }else{ 
                if($file!="." and $file!=".."){ 
                    $dirInfo[1]++; 
                    //$fd = fopen ("$directory/$file", "r"); 
                    $fileValue = file_get_contents("$directory/$file"); 
                    //fclose ($fd); 
                    $this -> addFile($fileValue, "$fileDir$file"); 
                } 
            } 
        } 
        $myDir->close(); 
    } 
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); 
} 
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 = "\x50\x4b\x03\x04"; 
$fr .= "\x14\x00"; // ver needed to extract 
$fr .= "\x00\x00"; // gen purpose bit flag 
$fr .= "\x08\x00"; // 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 = "\x50\x4b\x01\x02"; 
$cdrec .= "\x00\x00"; // version made by 
$cdrec .= "\x14\x00"; // version needed to extract 
$cdrec .= "\x00\x00"; // gen purpose bit flag 
$cdrec .= "\x08\x00"; // 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; 
} 
function filezip(){ 
$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 
"\x00\x00"; // .zip file comment length 
} 
} 
?>

zip.php文件打包
PHP 相关文章推荐
PHP Memcached + APC + 文件缓存封装实现代码
Mar 11 PHP
php邮件发送,php发送邮件的类
Mar 24 PHP
解析关于java,php以及html的所有文件编码与乱码的处理方法汇总
Jun 24 PHP
php中opendir函数用法实例
Nov 15 PHP
php使用MySQL保存session会话的方法
Jun 26 PHP
PHP简单操作MongoDB的方法(安装及增删改查)
May 26 PHP
PHP正则替换函数preg_replace()报错:Notice Use of undefined constant的解决方法分析
Feb 04 PHP
Yii框架创建cronjob定时任务的方法分析
May 23 PHP
PHP结合Vue实现滚动底部加载效果
Dec 17 PHP
PHP有序表查找之二分查找(折半查找)算法示例
Feb 09 PHP
PHP基于GD2函数库实现验证码功能示例
Jan 27 PHP
laravel 使用auth编写登录的方法
Sep 30 PHP
php入门教程 精简版
Dec 13 #PHP
php实现的仿阿里巴巴实现同类产品翻页
Dec 11 #PHP
Php Mssql操作简单封装支持存储过程
Dec 11 #PHP
php smarty模版引擎中变量操作符及使用方法
Dec 11 #PHP
phpmyadmin导入(import)文件限制的解决办法
Dec 11 #PHP
php smarty模版引擎中的缓存应用
Dec 11 #PHP
php5 图片验证码实现代码
Dec 11 #PHP
You might like
PHP一些常用的正则表达式字符的一些转换
2008/07/29 PHP
php阿拉伯数字转中文人民币大写
2015/12/21 PHP
PHP ElasticSearch做搜索实例讲解
2020/02/05 PHP
Javascript实例教程(19) 使用HoTMetal(2)
2006/12/23 Javascript
JavaScript 函数式编程的原理
2009/10/16 Javascript
js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)
2012/12/27 Javascript
文字垂直滚动之javascript代码
2015/07/29 Javascript
jQuery Validate验证框架经典大全
2015/09/23 Javascript
深入浅析Nodejs的Http模块
2017/06/20 NodeJs
JS库之Three.js 简易入门教程(详解之一)
2017/09/13 Javascript
使用canvas实现一个vue弹幕组件功能
2018/11/30 Javascript
JavaScript常见鼠标事件与用法分析
2019/01/03 Javascript
Vue实现商品飞入购物车效果(电商项目)
2019/11/26 Javascript
node.js使用http模块创建服务器和客户端完整示例
2020/02/10 Javascript
JavaScript面向对象核心知识与概念归纳整理
2020/05/09 Javascript
浅谈Python中的闭包
2015/07/08 Python
Python脚本实时处理log文件的方法
2016/11/21 Python
Python使用三种方法实现PCA算法
2017/12/12 Python
Python数据拟合与广义线性回归算法学习
2017/12/22 Python
python解析含有重复key的json方法
2019/01/22 Python
Python 的字典(Dict)是如何存储的
2019/07/05 Python
Python及Pycharm安装方法图文教程
2019/08/05 Python
Python中url标签使用知识点总结
2020/01/16 Python
python在不同条件下的输入与输出
2020/02/13 Python
Python如何读写字节数据
2020/08/05 Python
适合各种场合的美食礼品:Harry & David
2016/08/03 全球购物
Marriott中国:万豪国际酒店查询预订
2016/09/02 全球购物
ECCO爱步加拿大官网:北欧丹麦鞋履及皮具品牌
2017/07/08 全球购物
美国性感内衣店:Yandy
2018/06/12 全球购物
什么是设计模式
2012/06/17 面试题
英文简历中的自荐信范文
2013/12/14 职场文书
基层党组织公开承诺书
2014/03/28 职场文书
社区综治工作汇报
2014/10/27 职场文书
高一军训决心书
2015/02/05 职场文书
党员学习中国梦心得体会
2016/01/05 职场文书
Ruby序列化和持久化存储 Marshal和Pstore介绍
2022/04/18 Ruby