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 相关文章推荐
PHP4 与 MySQL 交互使用
Oct 09 PHP
php win下Socket方式发邮件类
Aug 21 PHP
PHP实现域名whois查询的代码(数据源万网、新网)
Feb 22 PHP
PHP中开发XML应用程序之基础篇 添加节点 删除节点 查询节点 查询节
Jul 09 PHP
php中url函数介绍及使用示例
Feb 13 PHP
CodeIgniter框架过滤HTML危险代码
Jun 12 PHP
PIGCMS 如何关闭聊天机器人
Feb 12 PHP
Zend Framework入门教程之Zend_Db数据库操作详解
Dec 08 PHP
[原创]PHP实现字节数Byte转换为KB、MB、GB、TB的方法
Aug 31 PHP
PHP实现搜索时记住状态的方法示例
May 11 PHP
Yii2框架加载css和js文件的方法分析
May 25 PHP
laravel-admin 后台表格筛选设置默认的查询日期方法
Oct 03 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
关于文本留言本的分页代码
2006/10/09 PHP
初学CAKEPHP 基础教程
2009/11/02 PHP
php中隐形字符65279(utf-8的BOM头)问题
2014/08/16 PHP
php gd等比例缩放压缩图片函数
2016/06/12 PHP
PHP实现的注册,登录及查询用户资料功能API接口示例
2017/06/06 PHP
PHP实现的Redis多库选择功能单例类
2017/07/27 PHP
Laravel框架中缓存的使用方法分析
2019/09/06 PHP
javascript 播放器 控制
2007/01/22 Javascript
javascript入门·对象属性方法大总结
2007/10/01 Javascript
Extjs ajax同步请求时post方式参数发送方式
2009/08/05 Javascript
jQuery点击后一组图片左右滑动的实现代码
2012/08/16 Javascript
禁止你的左键复制实用技巧
2013/01/04 Javascript
JavaScript sub方法入门实例(把字符串显示为下标)
2014/10/17 Javascript
js绘制圆形和矩形的方法
2015/08/05 Javascript
Node.js编写组件的三种实现方式
2016/02/25 Javascript
jquery层级选择器的实现(匹配后代元素div)
2016/09/05 Javascript
使用开源工具制作网页验证码的方法
2016/10/17 Javascript
Vue封装的组件全局注册并引用
2019/07/24 Javascript
解决qrcode.js生成二维码时必须定义一个空div的问题
2020/07/09 Javascript
[12:21]VICI vs TNC (BO3)
2018/06/07 DOTA
[53:36]Liquid vs VP Supermajor决赛 BO 第三场 6.10
2018/07/05 DOTA
python简单获取数组元素个数的方法
2015/07/13 Python
解决python 文本过滤和清理问题
2019/08/28 Python
Python 字符串、列表、元组的截取与切片操作示例
2019/09/17 Python
django创建超级用户过程解析
2019/09/18 Python
解决Python列表字符不区分大小写的问题
2019/12/19 Python
Python3如何在Windows和Linux上打包
2020/02/25 Python
如何使用Python自动生成报表并以邮件发送
2020/10/15 Python
Python 转移文件至云对象存储的方法
2021/02/07 Python
爱尔兰领先的在线体育用品零售商:theGAAstore
2018/04/16 全球购物
美国山地自行车、露营、户外装备和服装购物网站:Aventuron
2018/05/05 全球购物
给酒店员工的表扬信
2014/01/11 职场文书
街道党风廉政建设调研报告
2015/01/01 职场文书
2015年销售人员工作总结
2015/04/07 职场文书
初任公务员培训心得体会
2016/01/08 职场文书
如何在centos上使用yum安装rabbitmq-server
2021/03/31 Servers