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中两种缩放图片的函数,为图片添加水印
Jun 14 PHP
解析php中的escape函数
Jun 29 PHP
thinkphp实现上一篇与下一篇的方法
Dec 08 PHP
腾讯微博提示missing parameter errorcode 102 错误的解决方法
Dec 22 PHP
smarty模板引擎中自定义函数的方法
Jan 22 PHP
PHP使用正则表达式获取微博中的话题和对象名
Jul 18 PHP
PHP的关于变量和日期处理的一些面试题目整理
Aug 10 PHP
基于ThinkPHP实现批量删除
Dec 18 PHP
Thinkphp单字母函数使用指南
May 08 PHP
php使用number_format函数截取小数的方法分析
May 27 PHP
thinkPHP5.0框架引入Traits功能实例分析
Mar 18 PHP
laravel 解决后端无法获取到前端Post过来的值问题
Oct 22 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
javascript 小型动画组件与实现代码
2010/06/02 PHP
PHP的explode和implode的使用说明
2011/07/17 PHP
php在linux下检测mysql同步状态的方法
2015/01/15 PHP
PHP生成随机字符串(3种方法)
2015/09/25 PHP
php7安装yar扩展的方法详解
2017/08/03 PHP
载入进度条 效果
2006/07/08 Javascript
基于jquery的$.ajax async使用
2011/10/19 Javascript
jquery中animate动画积累的解决方法
2013/10/05 Javascript
javascript实现Table排序的方法
2015/05/15 Javascript
javascript简单判断输入内容是否合法的方法
2016/05/11 Javascript
bootstrap 设置checkbox部分选中效果
2017/04/20 Javascript
详解node-ccap模块生成captcha验证码
2017/07/01 Javascript
ionic使用angularjs表单验证(模板验证)
2018/12/12 Javascript
NestJs 静态目录配置详解
2019/03/12 Javascript
Element-ui自定义table表头、修改列标题样式、添加tooltip、:render-header使用
2019/04/11 Javascript
js module大战
2019/04/19 Javascript
vue增加强缓存和版本号的实现方法
2019/05/01 Javascript
python 七种邮件内容发送方法实例
2014/04/22 Python
python使用range函数计算一组数和的方法
2015/05/07 Python
python编写分类决策树的代码
2017/12/21 Python
利用css3实现的简单的鼠标悬停按钮
2014/11/04 HTML / CSS
Sneaker Studio法国:购买运动鞋
2018/06/08 全球购物
Android面试题附答案
2014/12/08 面试题
毕业生自荐书模版
2014/01/04 职场文书
安全生产检讨书
2014/01/21 职场文书
期末自我鉴定
2014/02/02 职场文书
教师学习三严三实心得体会
2014/10/13 职场文书
质监局领导班子践行群众路线整改方案
2014/10/26 职场文书
四风专项整治工作情况汇报
2014/10/28 职场文书
2014年人事行政工作总结
2014/12/03 职场文书
颐和园英文导游词
2015/01/30 职场文书
新员工试用期工作总结2015
2015/05/28 职场文书
同事欢送会致辞
2015/07/31 职场文书
企业团队精神心得体会
2016/01/19 职场文书
压缩Redis里的字符串大对象操作
2021/06/23 Redis
教你如何让spark sql写mysql的时候支持update操作
2022/02/15 MySQL