一个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的无限分类实现想法~
Jan 02 PHP
phpMyAdmin 安装教程全攻略
Mar 19 PHP
php access 数据连接与读取保存编辑数据的实现代码
May 12 PHP
怎样使用php与jquery设置和读取cookies
Aug 08 PHP
php可应用于面包屑导航的递归寻找家谱树实现方法
Feb 02 PHP
Laravel 5框架学习之用户认证
Apr 09 PHP
php获取本周星期一具体日期的方法
Apr 20 PHP
PHP生成唯一订单号
Jul 05 PHP
Centos PHP 扩展Xchche的安装教程
Jul 09 PHP
Zend Framework入门应用实例详解
Dec 11 PHP
老生常谈PHP 文件写入和读取(必看篇)
May 22 PHP
PHP中用Trait封装单例模式的实现
Dec 18 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 图片上添加透明度渐变的效果
2009/06/29 PHP
深入理解PHP之数组(遍历顺序)  Laruence原创
2012/06/13 PHP
php小技巧之过滤ascii控制字符
2014/05/14 PHP
php json相关函数用法示例
2017/03/28 PHP
PHP实现图的邻接矩阵表示及几种简单遍历算法分析
2017/11/24 PHP
PHP定义字符串的四种方式详解
2018/02/06 PHP
javascript背投广告代码的完善
2008/04/08 Javascript
用jQuery技术实现Tab页界面之二
2009/09/21 Javascript
jQuery动态添加、删除元素的方法
2014/01/09 Javascript
Firefox中使用outerHTML的2种解决方法
2014/06/07 Javascript
JQuery中DOM实现事件移除的方法
2015/06/13 Javascript
js随机生成26个大小写字母
2016/02/12 Javascript
JS实现的验证身份证及获取地区功能示例
2017/01/16 Javascript
js中小数向上取整数,向下取整数,四舍五入取整数的实现(必看篇)
2017/02/13 Javascript
JavaScript实现的原生态兼容IE6可调可控滚动文字功能详解
2017/09/19 Javascript
jQuery实现B2B网站后台管理系统侧导航
2020/07/08 jQuery
Python性能优化的20条建议
2014/10/25 Python
python使用KNN算法识别手写数字
2019/04/25 Python
Python直接赋值、浅拷贝与深度拷贝实例分析
2019/06/18 Python
python实现中文文本分句的例子
2019/07/15 Python
python 字典套字典或列表的示例
2019/12/16 Python
Python求两个字符串最长公共子序列代码实例
2020/03/05 Python
5 分钟读懂Python 中的 Hook 钩子函数
2020/12/09 Python
介绍一下木马病毒的种类
2015/07/26 面试题
甜品蛋糕店创业计划书范文
2014/02/06 职场文书
公司司机岗位职责
2014/02/07 职场文书
大学生秋游活动方案
2014/02/17 职场文书
工作决心书
2014/03/11 职场文书
毕业生找工作自荐书
2014/06/30 职场文书
《周恩来的四个昼夜》观后思想汇报范文两篇
2014/09/10 职场文书
授权委托书协议书
2014/10/16 职场文书
2015年禁毒工作总结
2015/04/30 职场文书
社区党员干部承诺书
2015/05/04 职场文书
刑事附带民事上诉状
2015/05/23 职场文书
python实战之用emoji表情生成文字
2021/05/08 Python
php png失真的原因及解决办法
2021/11/17 PHP