一个完美的PHP ZIP压缩类代码

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

For example:

 代码如下 复制代码
        $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 = "x50x4bx05x06x00x00x00x00";
    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]
                  . 'x' . $dtime[4] . $dtime[5]
                  . 'x' . $dtime[2] . $dtime[3]
                  . 'x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');

        $fr   = "x50x4bx03x04";
        $fr   .= "x14x00";            // ver needed to extract
        $fr   .= "x00x00";            // gen purpose bit flag
        $fr   .= "x08x00";            // 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 = "x50x4bx01x02";
        $cdrec .= "x00x00";                // version made by
        $cdrec .= "x14x00";                // version needed to extract
        $cdrec .= "x00x00";                // gen purpose bit flag
        $cdrec .= "x08x00";                // 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
            "x00x00";                             // .zip file comment length
    } // end of the 'file()' method

} // end of the 'PHPZip' class
?>

时间: 2024-09-27 12:33:35

一个完美的PHP ZIP压缩类代码的相关文章

PHP的一个完美GIF等比缩放类,附带去除缩放黑背景

 我这里没有判断文件类型,因为png和jpeg缩放后都不会出现黑色背景,就单独gif不行..查了下资料发现了一个完美的解决办法,附带有详解 现在写东西都喜欢封装成类.....大家调用一下就行了..我就不说怎么调用了  代码如下:<?php class resize_image{    private $o_img_width;//原图像宽度    private $o_img_height;//原图像高度    private $n_img_width;//新图像宽度    private $n

一个简单至极的PHP缓存类代码_php技巧

网上关于 PHP 缓存类的资料很多,不过这个类应该是我见过功能满足需求,但又无比简洁的一个.废话不多说,直接看代码吧!使用说明:1.实例化$cache = new Cache(); 2.设置缓存时间和缓存目录$cache = new Cache(60, '/any_other_path/'); 第一个参数是缓存秒数,第二个参数是缓存路径,根据需要配置. 默认情况下,缓存时间是 3600 秒,缓存目录是 cache/3.读取缓存$value = $cache->get('data_key'); 4

PHP的一个完美GIF等比缩放类,附带去除缩放黑背景_php实例

现在写东西都喜欢封装成类.....大家调用一下就行了..我就不说怎么调用了 复制代码 代码如下: <?phpclass resize_image{   private $o_img_width;//原图像宽度   private $o_img_height;//原图像高度   private $n_img_width;//新图像宽度   private $n_img_height;//新图像高度   private $o_img_file;//原图像文件   private $o_img_sou

一个完美php文件上传类使用实例

今天终于算是可以来更新一下paperen的网站,嗯--因为写毕设论文写累了所以就发表一篇关于上传文件类的东东吧,这个类也是自己写的,不知道对大家有没有用,如果觉得可以就拿去用吧.不过在编码上面还是没做好,自己是在utf8的页面将数据进行提交的,所以生成的文件如果保持原来的中文名字的话在文件夹中看到就是乱码的名字,如果不想出现乱码的话需要进行一下编码的转换.?  代码如下 复制代码 <?php define('NO_FILE', '不存在上传文件'); define('NOT_ALLOW_EXT'

命令行方式调用winrar对文件夹进行zip压缩示例代码

调用winRAR进行压缩 [csharp] view plain copy   using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   using System.Threading.Tasks;      namespace testZIPEXE   {       class Program       {           static void Main(s

asp Access数据备份,还原,压缩类代码_数据库相关

<!--#include file="config.asp" --> <!--#include file="Fun.asp" --> <% '数据库管理类 class Datas '备份 public sub Bk() Set fso=server.createobject("scripting.filesystemobject") fso.CopyFile Server.MapPath(SiteDataPath),

一个完美的JavaScript操作COOKIE类

 代码如下 复制代码 代码 /**提供客户端cookie操作类    *  * @param string uniqueN 唯一标识  *  * @author (凹凸曼)lyc  * @email jar-c@163.com  *  */ var cacheLY = function(uniqueN){     var uniqueN = (typeof(uniqueN) != "string") ? "" : "uniqueN_" + uni

asp Access数据备份,还原,压缩类代码

<!--#include file="config.asp" --> <!--#include file="Fun.asp" --> <% '数据库管理类 class Datas '备份 public sub Bk() Set fso=server.createobject("scripting.filesystemobject") fso.CopyFile Server.MapPath(SiteDataPath),

一个PHP压缩类,在线压缩文件

本文转自IT摆渡网欢迎转载,请标明出处 更多php文章请阅读 php开发 PHP压缩类:用于在线压缩文件.文档.目录等,附有使用方法,不想了解类原理的可直接按使用方法调用该类: <?php //PHP压缩类代码开始 class PHPZip{ function Zip($dir, $zipfilename) { if (@function_exists('gzcompress')) { $curdir = getcwd(); if (is_array($dir)) { $filelist = $