一个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 相关文章推荐
文章推荐系统(三)
Oct 09 PHP
比较时间段一与时间段二是否有交集的php函数
May 31 PHP
PHP中的错误处理、异常处理机制分析
May 07 PHP
php中如何使对象可以像数组一样进行foreach循环
Aug 09 PHP
19个超实用的PHP代码片段
Mar 14 PHP
PHP  Yii清理缓存的实现方法
Nov 10 PHP
php die()与exit()的区别实例详解
Dec 03 PHP
详解php几行代码实现CSV格式文件输出
Jul 01 PHP
php ajax confirm 删除实例详解
Mar 06 PHP
Discuz不使用插件实现简单的打赏功能
Mar 21 PHP
JS操作XML中DTD介绍及使用方法分析
Jul 04 PHP
php输出文字乱码的解决方法
Oct 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
批量修改RAR文件注释的php代码
2010/11/20 PHP
php curl模拟post提交数据示例
2013/12/31 PHP
PHP防止刷新重复提交页面的示例代码
2015/11/11 PHP
laravel-admin 管理平台获取当前登陆用户信息的例子
2019/10/08 PHP
javascript Split方法,indexOf方法、lastIndexOf 方法和substring 方法
2009/03/21 Javascript
WEB 浏览器兼容 推荐收藏
2010/05/14 Javascript
jquery下checked取值问题的解决方法
2012/08/09 Javascript
jquery中对于批量deferred的处理方法
2014/01/22 Javascript
jquery实现动态画圆
2014/12/04 Javascript
jQuery后代选择器用法实例
2014/12/23 Javascript
JQuery实现防止退格键返回的方法
2015/02/12 Javascript
javascript多行字符串的简单实现方式
2015/05/04 Javascript
浅谈JavaScript 函数参数传递到底是值传递还是引用传递
2016/08/23 Javascript
Vue Router去掉url中默认的锚点#
2018/08/01 Javascript
vue2.0 可折叠列表 v-for循环展示的实例
2018/09/07 Javascript
vue动态绑定class选中当前列表变色的方法示例
2018/12/19 Javascript
vue路由切换时取消之前的所有请求操作
2020/09/01 Javascript
vue-amap根据地址回显地图并mark的操作
2020/11/03 Javascript
在SAE上部署Python的Django框架的一些问题汇总
2015/05/30 Python
python 类详解及简单实例
2017/03/24 Python
python绘制多个曲线的折线图
2020/03/23 Python
Python实现定时执行任务的三种方式简单示例
2019/03/30 Python
Python3使用Matplotlib 绘制精美的数学函数图形
2019/04/11 Python
提升Python程序性能的7个习惯
2019/04/14 Python
CentOS7下安装python3.6.8的教程详解
2020/01/03 Python
Python类中的装饰器在当前类中的声明与调用详解
2020/04/15 Python
Python读取多列数据以及用matplotlib制作图表方法实例
2020/09/23 Python
如何在python中处理配置文件代码实例
2020/09/27 Python
PatPat德国:妈妈的每日优惠
2019/10/02 全球购物
阿联酋彩妆品牌:OUD MILANO
2019/10/06 全球购物
农村葬礼主持词
2014/03/31 职场文书
先进教师个人事迹材料
2014/12/15 职场文书
2015中学政教处工作总结
2015/07/22 职场文书
小学语文教师竞聘演讲稿范文
2019/08/09 职场文书
Nginx 反向代理解决跨域问题多种情况分析
2022/01/18 Servers
Python中Matplotlib的点、线形状、颜色以及绘制散点图
2022/04/07 Python