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 29 PHP
PHP 分页原理分析,大家可以看看
Dec 21 PHP
利用PHP实现智能文件类型检测的实现代码
Aug 02 PHP
比file_get_contents稳定的curl_get_contents分享
Jan 11 PHP
php的ajax简单实例
Feb 27 PHP
php序列化函数serialize() 和 unserialize() 与原生函数对比
May 08 PHP
PHP中SSO Cookie登录分析和实现
Nov 06 PHP
php验证码生成代码
Nov 11 PHP
php禁用函数设置及查看方法详解
Jul 25 PHP
PHP的自定义模板引擎
Mar 24 PHP
浅谈php调用python文件
Mar 29 PHP
PHP基于swoole多进程操作示例
Aug 12 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 无限极分类
2008/03/27 PHP
三种php连接access数据库方法
2013/11/11 PHP
PHP中soap的用法实例
2014/10/24 PHP
laravel-admin 实现给grid的列添加行数序号的方法
2019/10/08 PHP
让IE6支持min-width和max-width的方法
2010/06/25 Javascript
js利用数组length属性清空和截短数组的小例子
2014/01/15 Javascript
JavaScript排序算法之希尔排序的2个实例
2014/04/04 Javascript
手机端页面rem宽度自适应脚本
2015/05/20 Javascript
javascript实现图片轮播效果
2016/01/20 Javascript
JS实现图片平面旋转的方法
2016/03/01 Javascript
纯JS单页面赛车游戏制作代码分享
2017/03/03 Javascript
详解微信开发中snsapi_base和snsapi_userinfo及静默授权的实现
2017/03/11 Javascript
JavaScript中undefined和null的区别
2017/05/03 Javascript
Ionic2开发环境搭建教程
2020/08/20 Javascript
vue中实现先请求数据再渲染dom分享
2018/03/17 Javascript
JavaScript实现构造json数组的方法分析
2018/08/17 Javascript
layUI实现列表查询功能
2019/07/27 Javascript
vue单应用在ios系统中实现微信分享功能操作
2020/09/07 Javascript
详解JavaScript之Array.reduce源码解读
2020/11/01 Javascript
Python中用sleep()方法操作时间的教程
2015/05/22 Python
Python 处理图片像素点的实例
2019/01/08 Python
深入浅析python 协程与go协程的区别
2019/05/09 Python
11个Python3字典内置方法大全与示例汇总
2019/05/13 Python
pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换
2020/01/13 Python
keras自动编码器实现系列之卷积自动编码器操作
2020/07/03 Python
Pycharm2020.1安装中文语言插件的详细教程(不需要汉化)
2020/08/07 Python
python+django+selenium搭建简易自动化测试
2020/08/19 Python
详解纯CSS3制作的20种loading动效
2017/07/05 HTML / CSS
HTML5触摸事件演化tap事件介绍
2016/03/25 HTML / CSS
澳洲本土太阳镜品牌:Quay Australia
2019/07/29 全球购物
2014企业领导班子四风对照检查材料思想汇报
2014/09/17 职场文书
社区志愿服务活动感想
2015/08/07 职场文书
MySql学习笔记之事务隔离级别详解
2021/05/12 MySQL
Python数据分析入门之数据读取与存储
2021/05/13 Python
sass 常用备忘案例详解
2021/09/15 HTML / CSS