一个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 相关文章推荐
一个好用的分页函数
Nov 16 PHP
使用TinyButStrong模板引擎来做WEB开发
Mar 16 PHP
学习使用curl采集curl使用方法
Jan 11 PHP
基于MySQL分区性能的详细介绍
May 02 PHP
php打开远程文件的方法和风险及解决方法
Nov 12 PHP
ThinkPHP提交表单时默认自动转义的解决方法
Nov 25 PHP
php获取指定(访客)IP所有信息(地址、邮政编码、国家、经纬度等)的方法
Jul 06 PHP
PHP模板引擎Smarty中变量的使用方法示例
Apr 11 PHP
Yii2创建多界面主题(Theme)的方法
Oct 08 PHP
使用PHP下载CSS文件中的所有图片【几行代码即可实现】
Dec 14 PHP
php递归函数怎么用才有效
Feb 24 PHP
PHP基于redis计数器类定义与用法示例
Feb 08 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中函数内引用全局变量的方法
2008/10/20 PHP
php通过隐藏表单控件获取到前两个页面的url
2014/09/09 PHP
jQuery UI Autocomplete 1.8.16 中文输入修正代码
2012/04/16 Javascript
JS获取当前网址、主机地址项目根路径
2013/11/19 Javascript
javascript动态创建及删除元素的方法
2014/12/22 Javascript
jQuery 选择器详解
2015/01/19 Javascript
iframe中子父类窗口调用JS的方法及注意事项
2015/08/25 Javascript
Javascript农历与公历相互转换的简单实例
2016/10/09 Javascript
Bootstrap Modal遮罩弹出层代码分享
2016/11/21 Javascript
Bootstarp 基础教程之表单部分实例代码
2017/02/03 Javascript
js中document.referrer实现移动端返回上一页
2017/02/22 Javascript
详解Node.js串行化流程控制
2017/05/04 Javascript
Chrome调试折腾记之JS断点调试技巧
2017/09/11 Javascript
vue一个页面实现音乐播放器的示例
2018/02/06 Javascript
深入了解query和params的使用区别
2019/06/24 Javascript
JavaScript实现秒杀时钟倒计时
2019/09/29 Javascript
在Python中用has_key()方法查找键是否存在的教程
2015/05/21 Python
Google开源的Python格式化工具YAPF的安装和使用教程
2016/05/31 Python
Python爬虫之模拟知乎登录的方法教程
2017/05/25 Python
Anaconda 离线安装 python 包的操作方法
2018/06/11 Python
Python subprocess模块功能与常见用法实例详解
2018/06/28 Python
解决win64 Python下安装PIL出错问题(图解)
2018/09/03 Python
Python结合百度语音识别实现实时翻译软件的实现
2021/01/18 Python
HTML5 在canvas中绘制矩形附效果图
2014/06/23 HTML / CSS
办公室文秘自我评价
2013/09/21 职场文书
十佳班主任事迹材料
2014/01/18 职场文书
代办委托书怎样写
2014/04/08 职场文书
病媒生物防治方案
2014/05/13 职场文书
房地产开发项目建议书
2014/05/16 职场文书
农业局党的群众路线教育实践活动整改方案
2014/09/20 职场文书
2015年小学数学教师工作总结
2015/05/20 职场文书
法律意见书范文
2015/05/20 职场文书
有关花店创业的计划书模板
2019/08/27 职场文书
完美解决golang go get私有仓库的问题
2021/05/05 Golang
解决Navicat for Mysql连接报错1251的问题(连接失败)
2021/05/27 MySQL
Go获取两个时区的时间差
2022/04/20 Golang