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 相关文章推荐
php5新改动之短标记启用方法
Sep 11 PHP
php curl常见错误:SSL错误、bool(false)
Dec 28 PHP
如何使用Strace调试工具
Jun 03 PHP
使用php验证复选框有效性的示例
Nov 13 PHP
PHP获取时间排除周六、周日的两个方法
Jun 30 PHP
php+mysqli预处理技术实现添加、修改及删除多条数据的方法
Jan 30 PHP
PHP图形操作之Jpgraph学习笔记
Dec 25 PHP
PHP的Yii框架中行为的定义与绑定方法讲解
Mar 18 PHP
基于php流程控制语句和循环控制语句(讲解)
Oct 23 PHP
php递归函数怎么用才有效
Feb 24 PHP
laravel框架使用极光推送消息操作示例
Feb 15 PHP
PHP中的输出echo、print、printf、sprintf、print_r和var_dump的示例代码
Dec 01 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
西德产收音机
2021/03/01 无线电
Php 构造函数construct的前下划线是双的_
2009/12/08 PHP
简单的方法让你的后台登录更加安全(php中加session验证)
2012/08/22 PHP
js限制checkbox勾选的个数以及php获取多个checkbbox的方法深入解析
2013/07/18 PHP
php rmdir使用递归函数删除非空目录实例详解
2016/10/20 PHP
实例解析php的数据类型
2018/10/24 PHP
PHP设计模式(一)工厂模式Factory实例详解【创建型】
2020/05/02 PHP
jQuery 第二课 操作包装集元素代码
2010/03/14 Javascript
javascript 禁用IE工具栏,导航栏等等实现代码
2013/04/01 Javascript
再谈javascript原型继承
2014/11/10 Javascript
JS选项卡动态替换banner图片路径的方法
2015/05/11 Javascript
jQuery div拖拽用法实例
2016/01/14 Javascript
微信小程序技巧之show内容展示,上传文件编码问题
2017/01/23 Javascript
Vue中的v-cloak使用解读
2017/03/27 Javascript
JS实现预加载视频音频/视频获取截图(返回canvas截图)
2017/10/09 Javascript
jQuery实现的简单拖拽功能示例【测试可用】
2018/08/14 jQuery
JS实现滑动导航效果
2020/01/14 Javascript
vue实现下载文件流完整前后端代码
2020/11/17 Vue.js
Python实现OpenCV的安装与使用示例
2018/03/30 Python
python 使用re.search()筛选后 选取部分结果的方法
2018/11/28 Python
python运行时强制刷新缓冲区的方法
2019/01/14 Python
在Python中使用MySQL--PyMySQL的基本使用方法
2019/11/19 Python
flask项目集成swagger的方法
2020/12/09 Python
python 递归相关知识总结
2021/03/03 Python
印度尼西亚最大的电商平台:Tokopedia(印尼版淘宝)
2017/12/02 全球购物
自考毕业自我鉴定范文
2013/10/27 职场文书
网络信息管理员岗位职责
2014/01/05 职场文书
公司授权委托书
2014/04/04 职场文书
《桂花雨》教学反思
2014/04/12 职场文书
秘书英文求职信
2014/04/16 职场文书
小学生个人先进事迹材料
2014/05/08 职场文书
2014年技术员工作总结
2014/11/18 职场文书
优秀大学生事迹材料
2014/12/24 职场文书
致三级跳运动员加油稿
2015/07/21 职场文书
优秀学生干部主要事迹材料
2015/11/04 职场文书
2016年教育局“我们的节日——端午节”主题活动总结
2016/04/01 职场文书