一个PHP的ZIP压缩类分享


Posted in PHP onMay 04, 2014

功能:将文件压缩成zip,或者rar的压缩包。后缀名可以自定义。

使用方法:首先实例化,然后传参。两个参数。第一个关于你文件地址的一个Array。第二个是要你要保存的压缩包文件的绝对地址。

使用例子:

        $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的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 = "\x50\x4b\x05\x06\x00\x00\x00\x00";
    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]
                   <a href="http://wutransfer.com/western-union-locations-in-russia-taiynsha/">Western union point</a> .  '\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;
    } // 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
            "\x00\x00";                             // .zip file comment length
    } // end of the 'file()' method
} // end of the 'PHPZip' class
?>
PHP 相关文章推荐
php 各种应用乱码问题的解决方法
May 09 PHP
一些php项目中比较通用的php自建函数的详解
Jun 06 PHP
PHP 获取远程文件大小的3种解决方法
Jul 11 PHP
PHP中的output_buffering详细介绍
Sep 27 PHP
PHP实现的增强性mhash函数
May 27 PHP
PHP+redis实现添加处理投票的方法
Nov 14 PHP
浅谈PHP检查数组中是否存在某个值 in_array 函数
Jun 13 PHP
thinkPHP5.0框架简单配置作用域的方法
Mar 17 PHP
PHP 无限级分类
May 04 PHP
PHP中使用mpdf 导出PDF文件的实现方法
Oct 22 PHP
浅谈laravel aliases别名的原理
Oct 24 PHP
php+laravel依赖注入知识点总结
Nov 04 PHP
PHP生成自定义长度随机字符串的函数分享
May 04 #PHP
PHP把空格、换行符、中文逗号等替换成英文逗号的正则表达式
May 04 #PHP
PHP中使用FFMPEG获取视频缩略图和视频总时长实例
May 04 #PHP
PHP错误WARNING: SESSION_START() [FUNCTION.SESSION-START]解决方法
May 04 #PHP
PHP使用CURL获取302跳转后的地址实例
May 04 #PHP
Fatal error: session_start(): Failed to initialize storage module: files问题解决方法
May 04 #PHP
PHPThumb图片处理实例
May 03 #PHP
You might like
PHP数组及条件,循环语句学习
2012/11/11 PHP
Codeigniter整合Tank Auth权限类库详解
2014/06/12 PHP
以实例全面讲解PHP中多进程编程的相关函数的使用
2015/08/18 PHP
Yii2 rbac权限控制之菜单menu实例教程
2016/04/28 PHP
jquery.jstree 增加节点的双击事件代码
2010/07/27 Javascript
解析使用JS 清空File控件的路径值
2013/07/08 Javascript
jQuery中position()方法用法实例
2015/01/16 Javascript
js电话号码验证方法
2015/09/28 Javascript
js如何改变文章的字体大小
2016/01/08 Javascript
Vue filters过滤器的使用方法
2017/07/14 Javascript
JavaScript字符串转数字的5种方法及遇到的坑
2018/07/16 Javascript
详解javascript replace高级用法
2019/02/17 Javascript
Node.js 实现远程桌面监控的方法步骤
2019/07/02 Javascript
Android 自定义view仿微信相机单击拍照长按录视频按钮
2019/07/19 Javascript
layui 数据表格复选框实现单选功能的例子
2019/09/19 Javascript
[02:10]DOTA2亚洲邀请赛 EG战队出场宣传片
2015/02/07 DOTA
利用python和百度地图API实现数据地图标注的方法
2019/05/13 Python
python next()和iter()函数原理解析
2020/02/07 Python
canvas实现圆绘制的示例代码
2019/09/11 HTML / CSS
美国学校校服,儿童和婴儿服装:Cookie’s Kids
2016/10/14 全球购物
Mytheresa美国官网:德国知名的女性奢侈品电商
2017/05/27 全球购物
婴儿地球:Baby Earth
2018/12/25 全球购物
北京天润融通.net面试题笔试题
2012/02/20 面试题
生物科学专业个人求职信范文
2013/12/07 职场文书
大学毕业感言100字
2014/02/03 职场文书
学习全国两会精神心得体会范文
2014/03/17 职场文书
意外伤害赔偿协议书
2014/09/16 职场文书
私用公车造成事故检讨书
2014/11/16 职场文书
2014年销售工作总结与计划
2014/12/01 职场文书
毕业论文致谢格式模板
2015/05/14 职场文书
党员发展大会主持词
2015/07/03 职场文书
2015年秋季运动会前导词
2015/07/20 职场文书
Jsonp劫持学习
2021/04/01 PHP
Python 流媒体播放器的实现(基于VLC)
2021/04/28 Python
详解gantt甘特图可拖拽、编辑(vue、react都可用 highcharts)
2021/11/27 Vue.js
经典《舰娘》游改全新动画预告 预定11月开播
2022/04/01 日漫