php文件压缩之PHPZip类用法实例


Posted in PHP onJune 18, 2015

本文实例讲述了php文件压缩之PHPZip类用法。分享给大家供大家参考。具体如下:

<?php
//
// PHPZip v1.2 by Sext (sext@neud.net) 
//
// 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
?>

使用方法:

<?php
$z = new PHPZip(); //新建立一个zip的类
//方法一:
$z -> Zip("", "out1.zip"); //添加当前目录和子目录下的所有档案
//方法二:
$files=array('1.txt','gb.txt');
$files[]='5.txt';
$z -> Zip($files, "out2.zip"); //添加文件列表
//方法三:
$z -> Zip("/usr/local/sext/", "out3.zip"); //添加指定目录
?>

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
十天学会php之第八天
Oct 09 PHP
php 字符过滤类,用于过滤各类用户输入的数据
May 27 PHP
利用Memcached在php下实现session机制 替换PHP的原生session支持
Aug 21 PHP
PHP Class&amp;Object -- PHP 自排序二叉树的深入解析
Jun 25 PHP
PHP生成指定长度随机数最简洁的方法
Jul 14 PHP
PHP伪静态Rewrite设置之APACHE篇
Jul 30 PHP
php实现读取和写入tab分割的文件
Jun 01 PHP
谈谈你对Zend SAPIs(Zend SAPI Internals)的理解
Nov 10 PHP
详解PHP处理字符串类似indexof的方法函数
Jun 11 PHP
php+ajax实现异步上传文件或图片功能
Jul 18 PHP
PHP连接MySQL数据库并以json格式输出
May 21 PHP
laravel 出现command not found问题的解决方案
Oct 23 PHP
浅谈php中include文件变量作用域
Jun 18 #PHP
Apache连接PHP后无法启动问题解决思路
Jun 18 #PHP
php实现只保留mysql中最新1000条记录
Jun 18 #PHP
php使用COPY函数更新配置文件的方法
Jun 18 #PHP
ThinkPHP里用U方法调用js文件实例
Jun 18 #PHP
php实现mysql数据库分表分段备份
Jun 18 #PHP
php遍历树的常用方法汇总
Jun 18 #PHP
You might like
开发大型PHP项目的方法
2006/10/09 PHP
随机广告显示(PHP函数)
2006/10/09 PHP
几个php应用技巧
2008/03/27 PHP
浅谈php优化需要注意的地方
2014/11/27 PHP
php中动态调用函数的方法
2015/03/16 PHP
php入门教程之Zend Studio设置与开发实例
2016/09/09 PHP
用php实现分页效果的示例代码
2020/12/10 PHP
整理一些JavaScript的IE和火狐的兼容性注意事项
2011/03/17 Javascript
也说JavaScript中String类的replace函数
2011/09/22 Javascript
使用js对select动态添加和删除OPTION示例代码
2013/08/12 Javascript
在JS方法中返回多个值的方法汇总
2015/05/20 Javascript
JS模式之单例模式基本用法
2015/06/30 Javascript
vue中使用input[type=&quot;file&quot;]实现文件上传功能
2018/09/10 Javascript
JavaScript DOM常用操作代码汇总
2020/07/03 Javascript
vue 解决data中定义图片相对路径页面不显示的问题
2020/08/13 Javascript
关于小程序优化的一些建议(小结)
2020/12/10 Javascript
[09:31]2016国际邀请赛中国区预选赛Yao赛后采访 答题送礼
2016/06/27 DOTA
Python全局变量用法实例分析
2016/07/19 Python
Python实现邮件的批量发送的示例代码
2018/01/23 Python
Python处理文本换行符实例代码
2018/02/03 Python
用python处理MS Word的实例讲解
2018/05/08 Python
python 读取dicom文件,生成info.txt和raw文件的方法
2019/01/24 Python
Python实现的矩阵转置与矩阵相乘运算示例
2019/03/26 Python
利用CSS3实现的文字定时向上滚动
2016/08/29 HTML / CSS
用HTML5 Canvas API中的clearRect()方法实现橡皮擦功能
2016/03/15 HTML / CSS
浅谈html5 响应式布局
2014/12/24 HTML / CSS
详解快速开发基于 HTML5 网络拓扑图应用
2018/01/08 HTML / CSS
电子商务毕业生求职信
2013/11/10 职场文书
创业计划书如何吸引他人眼球
2014/01/10 职场文书
安全月活动总结
2014/05/05 职场文书
五水共治捐款倡议书
2014/05/14 职场文书
家庭困难证明
2014/10/12 职场文书
银行求职自荐信范文
2015/03/04 职场文书
关于实现中国梦的心得体会
2016/01/05 职场文书
NodeJs内存占用过高的排查实战记录
2021/05/10 NodeJs
CSS使用SVG实现动态分布的圆环发散路径动画
2022/12/24 HTML / CSS