一个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网站提速三大“软”招
Oct 09 PHP
php中get_meta_tags()、CURL与user-agent用法分析
Dec 16 PHP
PHP实现检测客户端是否使用代理服务器及其匿名级别
Jan 07 PHP
smarty模板引擎之配置文件数据和保留数据
Mar 30 PHP
php使用标签替换的方式生成静态页面
May 21 PHP
PHP基于cookie与session统计网站访问量并输出显示的方法
Jan 15 PHP
PHP数组游标实现对数组的各种操作详解
Jan 26 PHP
如何使用PHP给图片加水印
Oct 12 PHP
PHP 用session与gd库实现简单验证码生成与验证的类方法
Nov 15 PHP
php连接微软MSSQL(sql server)完全攻略
Nov 27 PHP
php实现的后台表格分页功能示例
Oct 23 PHP
thinkphp5 加载静态资源路径与常量的方法
Dec 24 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
虹吸式咖啡探讨–研磨
2021/03/03 冲泡冲煮
PHP连接SQLServer2005的实现方法(附ntwdblib.dll下载)
2012/07/02 PHP
解析php框架codeigniter中如何使用框架的session
2013/06/24 PHP
php实现utf-8转unicode函数分享
2015/01/06 PHP
9条PHP编程小知识及易犯的小错误
2015/01/22 PHP
WordPress中给媒体文件添加分类和标签的PHP功能实现
2015/12/31 PHP
PHP链表操作简单示例
2016/10/15 PHP
jQuery toggle()设置CSS样式
2009/11/05 Javascript
js检查页面上有无重复id的实现代码
2013/07/17 Javascript
jquery通过load获取文件的内容并跳到锚点的方法
2015/01/29 Javascript
jQuery插件scroll实现无缝滚动效果
2015/04/27 Javascript
包含中国城市的javascript对象实例
2015/08/03 Javascript
js获取url传值的方法
2015/12/18 Javascript
使用postMesssage()实现跨域iframe页面间的信息传递方法
2016/03/29 Javascript
浅谈js原生拖放
2016/11/21 Javascript
jQuery中的siblings()是什么意思(推荐)
2016/12/29 Javascript
基于zepto.js实现手机相册功能
2017/07/11 Javascript
javascript按钮禁用和启用的效果实例代码
2017/10/29 Javascript
Angular实现模版驱动表单的自定义校验功能(密码确认为例)
2018/05/17 Javascript
VUE中v-on:click事件中获取当前dom元素的代码
2018/08/22 Javascript
vue实现评论列表功能
2019/10/25 Javascript
python如何实现远程控制电脑(结合微信)
2015/12/21 Python
Python实现获取邮箱内容并解析的方法示例
2018/06/16 Python
Python更新所有已安装包的操作
2020/02/13 Python
浅谈python多线程和多线程变量共享问题介绍
2020/04/17 Python
Python使用re模块验证危险字符
2020/05/21 Python
马来西亚演唱会订票网站:StubHub马来西亚
2018/10/18 全球购物
英国最大的纸工艺品商店:CraftStash
2018/12/01 全球购物
芭比波朗加拿大官方网站:Bobbi Brown Cosmetics CA
2020/11/05 全球购物
DataList 能否分页,请问如何实现?
2015/05/03 面试题
高级护理专业大学生求职信
2013/10/24 职场文书
厂办主管岗位职责范本
2014/02/28 职场文书
2015年高考寄语或鼓励的话
2015/03/23 职场文书
2015年治庸问责工作总结
2015/07/27 职场文书
《最后一头战象》教学反思
2016/02/16 职场文书
《王者天下》第4季首话新剧照 4月9日正式开播
2022/04/07 日漫