php zip文件解压类代码

代码如下:

class zip
{
var $datasec, $ctrl_dir = array();
var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
var $old_offset = 0; var $dirs = Array(".");
function get_List($zip_name)
{
$zip = @fopen($zip_name, 'rb');
if(!$zip) return(0);
$centd = $this->ReadCentralDir($zip,$zip_name);
@rewind($zip);
@fseek($zip, $centd['offset']);
for ($i=0; $i<$centd['entries']; $i++)
{
$header = $this->ReadCentralFileHeaders($zip);
$header['index'] = $i;$info['filename'] = $header['filename'];
$info['stored_filename'] = $header['stored_filename'];
$info['size'] = $header['size'];$info['compressed_size']=$header['compressed_size'];
$info['crc'] = strtoupper(dechex( $header['crc'] ));
$info['mtime'] = $header['mtime']; $info['comment'] = $header['comment'];
$info['folder'] = ($header['external']==0x41FF0010||$header['external']==16)?1:0;
$info['index'] = $header['index'];$info['status'] = $header['status'];
$ret[]=$info; unset($header);
}
return $ret;
}
function Add($files,$compact)
{
if(!is_array($files[0])) $files=Array($files);
for($i=0;$files[$i];$i++){
$fn = $files[$i];
if(!in_Array(dirname($fn[0]),$this->dirs))
$this->add_Dir(dirname($fn[0]));
if(basename($fn[0]))
$ret[basename($fn[0])]=$this->add_File($fn[1],$fn[0],$compact);
}
return $ret;
}
function get_file()
{
$data = implode('', $this -> datasec);
$ctrldir = implode('', $this -> ctrl_dir);
return $data . $ctrldir . $this -> eof_ctrl_dir .
pack('v', sizeof($this -> ctrl_dir)).pack('v', sizeof($this -> ctrl_dir)).
pack('V', strlen($ctrldir)) . pack('V', strlen($data)) . "\x00\x00";
}
function add_dir($name)
{
$name = str_replace("\\", "/", $name);
$fr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
$fr .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
$fr .= pack("v", 0 ).$name.pack("V", 0).pack("V", 0).pack("V", 0);
$this -> datasec[] = $fr;
$new_offset = strlen(implode("", $this->datasec));
$cdrec = "\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00";
$cdrec .= pack("V",0).pack("V",0).pack("V",0).pack("v", strlen($name) );
$cdrec .= pack("v", 0 ).pack("v", 0 ).pack("v", 0 ).pack("v", 0 );
$ext = "\xff\xff\xff\xff";
$cdrec .= pack("V", 16 ).pack("V", $this -> old_offset ).$name;
$this -> ctrl_dir[] = $cdrec;
$this -> old_offset = $new_offset;
$this -> dirs[] = $name;
}
function add_File($data, $name, $compact = 1)
{
$name = str_replace('\\', '/', $name);
$dtime = dechex($this->DosTime());
$hexdtime = '\x' . $dtime[6] . $dtime[7].'\x'.$dtime[4] . $dtime[5]
. '\x' . $dtime[2] . $dtime[3].'\x'.$dtime[0].$dtime[1];
eval('$hexdtime = "' . $hexdtime . '";');
if($compact)
$fr = "\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00".$hexdtime;
else $fr = "\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00".$hexdtime;
$unc_len = strlen($data); $crc = crc32($data);
if($compact){
$zdata = gzcompress($data); $c_len = strlen($zdata);
$zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2);
}else{
$zdata = $data;
}
$c_len=strlen($zdata);
$fr .= pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
$fr .= pack('v', strlen($name)).pack('v', 0).$name.$zdata;
$fr .= pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
$this -> datasec[] = $fr;
$new_offset = strlen(implode('', $this->datasec));
if($compact)
$cdrec = "\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00";
else $cdrec = "\x50\x4b\x01\x02\x14\x00\x0a\x00\x00\x00\x00\x00";
$cdrec .= $hexdtime.pack('V', $crc).pack('V', $c_len).pack('V', $unc_len);
$cdrec .= pack('v', strlen($name) ).pack('v', 0 ).pack('v', 0 );
$cdrec .= pack('v', 0 ).pack('v', 0 ).pack('V', 32 );
$cdrec .= pack('V', $this -> old_offset );
$this -> old_offset = $new_offset;
$cdrec .= $name;
$this -> ctrl_dir[] = $cdrec;
return true;
}
function DosTime() {
$timearray = getdate();
if ($timearray['year'] < 1980) {
$timearray['year'] = 1980; $timearray['mon'] = 1;
$timearray['mday'] = 1; $timearray['hours'] = 0;
$timearray['minutes'] = 0; $timearray['seconds'] = 0;
}
return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) | ($timearray['hours'] << 11) |
($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
}
function Extract ( $zn, $to, $index = Array(-1) )
{
$ok = 0; $zip = @fopen($zn,'rb');
if(!$zip) return(-1);
$cdir = $this->ReadCentralDir($zip,$zn);
$pos_entry = $cdir['offset'];
if(!is_array($index)){ $index = array($index); }
for($i=0; $index[$i];$i++){
if(intval($index[$i])!=$index[$i]||$index[$i]>$cdir['entries'])
return(-1);
}
for ($i=0; $i<$cdir['entries']; $i++)
{
@fseek($zip, $pos_entry);
$header = $this->ReadCentralFileHeaders($zip);
$header['index'] = $i; $pos_entry = ftell($zip);
@rewind($zip); fseek($zip, $header['offset']);
if(in_array("-1",$index)||in_array($i,$index))
$stat[$header['filename']]=$this->ExtractFile($header, $to, $zip);
}
fclose($zip);
return $stat;
}
function ReadFileHeader($zip)
{
$binary_data = fread($zip, 30);
$data = unpack('vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $binary_data);
$header['filename'] = fread($zip, $data['filename_len']);
if ($data['extra_len'] != 0) {
$header['extra'] = fread($zip, $data['extra_len']);
} else { $header['extra'] = ''; }
$header['compression'] = $data['compression'];$header['size'] = $data['size'];
$header['compressed_size'] = $data['compressed_size'];
$header['crc'] = $data['crc']; $header['flag'] = $data['flag'];
$header['mdate'] = $data['mdate'];$header['mtime'] = $data['mtime'];
if ($header['mdate'] && $header['mtime']){
$hour=($header['mtime']&0xF800)>>11;$minute=($header['mtime']&0x07E0)>>5;
$seconde=($header['mtime']&0x001F)*2;$year=(($header['mdate']&0xFE00)>>9)+1980;
$month=($header['mdate']&0x01E0)>>5;$day=$header['mdate']&0x001F;
$header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
}else{$header['mtime'] = time();}
$header['stored_filename'] = $header['filename'];
$header['status'] = "ok";
return $header;
}
function ReadCentralFileHeaders($zip){
$binary_data = fread($zip, 46);
$header = unpack('vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $binary_data);
if ($header['filename_len'] != 0)
$header['filename'] = fread($zip,$header['filename_len']);
else $header['filename'] = '';
if ($header['extra_len'] != 0)
$header['extra'] = fread($zip, $header['extra_len']);
else $header['extra'] = '';
if ($header['comment_len'] != 0)
$header['comment'] = fread($zip, $header['comment_len']);
else $header['comment'] = '';
if ($header['mdate'] && $header['mtime'])
{
$hour = ($header['mtime'] & 0xF800) >> 11;
$minute = ($header['mtime'] & 0x07E0) >> 5;
$seconde = ($header['mtime'] & 0x001F)*2;
$year = (($header['mdate'] & 0xFE00) >> 9) + 1980;
$month = ($header['mdate'] & 0x01E0) >> 5;
$day = $header['mdate'] & 0x001F;
$header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
} else {
$header['mtime'] = time();
}
$header['stored_filename'] = $header['filename'];
$header['status'] = 'ok';
if (substr($header['filename'], -1) == '/')
$header['external'] = 0x41FF0010;
return $header;
}
function ReadCentralDir($zip,$zip_name)
{
$size = filesize($zip_name);
if ($size < 277) $maximum_size = $size;
else $maximum_size=277;
@fseek($zip, $size-$maximum_size);
$pos = ftell($zip); $bytes = 0x00000000;
while ($pos < $size)
{
$byte = @fread($zip, 1); $bytes=($bytes << 8) | Ord($byte);
if ($bytes == 0x504b0506){ $pos++; break; } $pos++;
}
$data=unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size',
fread($zip, 18));
if ($data['comment_size'] != 0)
$centd['comment'] = fread($zip, $data['comment_size']);
else $centd['comment'] = ''; $centd['entries'] = $data['entries'];
$centd['disk_entries'] = $data['disk_entries'];
$centd['offset'] = $data['offset'];$centd['disk_start'] = $data['disk_start'];
$centd['size'] = $data['size']; $centd['disk'] = $data['disk'];
return $centd;
}
function ExtractFile($header,$to,$zip)
{
$header = $this->readfileheader($zip);
if(substr($to,-1)!="/") $to.="/";
if(!@is_dir($to)) @mkdir($to,0777);
$pth = explode("/",dirname($header['filename']));
for($i=0;isset($pth[$i]);$i++){
if(!$pth[$i]) continue;
if(!is_dir($to.$pth[$i])) @mkdir($to.$pth[$i],0777);
}
if (!($header['external']==0x41FF0010)&&!($header['external']==16))
{
if ($header['compression']==0)
{
$fp = @fopen($to.$header['filename'], 'wb');
if(!$fp) return(-1);
$size = $header['compressed_size'];
while ($size != 0)
{
$read_size = ($size < 2048 ? $size : 2048);
$buffer = fread($zip, $read_size);
$binary_data = pack('a'.$read_size, $buffer);
@fwrite($fp, $binary_data, $read_size);
$size -= $read_size;
}
fclose($fp);
touch($to.$header['filename'], $header['mtime']);
}else{
$fp = @fopen($to.$header['filename'].'.gz','wb');
if(!$fp) return(-1);
$binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($header['compression']),
Chr(0x00), time(), Chr(0x00), Chr(3));
fwrite($fp, $binary_data, 10);
$size = $header['compressed_size'];
while ($size != 0)
{
$read_size = ($size < 1024 ? $size : 1024);
$buffer = fread($zip, $read_size);
$binary_data = pack('a'.$read_size, $buffer);
@fwrite($fp, $binary_data, $read_size);
$size -= $read_size;
}
$binary_data = pack('VV', $header['crc'], $header['size']);
fwrite($fp, $binary_data,8); fclose($fp);
$gzp = @gzopen($to.$header['filename'].'.gz','rb') or die("Cette archive est compress閑");
if(!$gzp) return(-2);
$fp = @fopen($to.$header['filename'],'wb');
if(!$fp) return(-1);
$size = $header['size'];
while ($size != 0)
{
$read_size = ($size < 2048 ? $size : 2048);
$buffer = gzread($gzp, $read_size);
$binary_data = pack('a'.$read_size, $buffer);
@fwrite($fp, $binary_data, $read_size);
$size -= $read_size;
}
fclose($fp); gzclose($gzp);
touch($to.$header['filename'], $header['mtime']);
@unlink($to.$header['filename'].'.gz');
}}
return true;
}
}
/***********************************/
class zipPeter{
    var $_zip_hander = null;
    function __construct(){

}
    function get_List($zip_name){
        $file_list = array();
        $this->_zip_hander = zip_open($zip_name);
        if ( $this->_zip_hander ) {
            while ( $zip_entry = zip_read($this->_zip_hander) ) {
                $file_list[] = array('filename'=>zip_entry_name($zip_entry),
                                    'size'=>zip_entry_filesize($zip_entry),
                                    'compressed_size'=>zip_entry_compressedsize($zip_entry)
                                    );
        }
            zip_close($this->_zip_hander);
        }
        return $file_list;
    }
    function Extract($zip_name,$folder_name){
        $this->_zip_hander = zip_open($zip_name);
        if ( !$this->checkDirAndMk($folder_name) ){
            return false;
        }
        if ( substr($folder_name,-1)!="/" ){
            $folder_name .= "/";
        }
        if ( $this->_zip_hander ) {
            while ( $zip_entry = zip_read($this->_zip_hander) ) {
                $file_info = array('filename'=>zip_entry_name($zip_entry),
                                    'size'=>zip_entry_filesize($zip_entry),
                                    'compressed_size'=>zip_entry_compressedsize($zip_entry)
                                    );
                $new_file_name = $folder_name.$file_info['filename'];
                $buf = "";
                if (zip_entry_open($this->_zip_hander, $zip_entry, "r")) {
                    $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    zip_entry_close($zip_entry);
                }
                if ( $fp = fopen($new_file_name,"w") ){
                    fwrite($fp,$buf);
                    fclose($fp);
                }
        }
            zip_close($this->_zip_hander);
            return true;
        }
        else {
            return false;
        }
    }
    /**
     * 检查目录是否存在,如果不存在是否建立
     *
     * @param string $dirname        完整的实际路径
     * @param bool $mk                如果不存在是否创建
     * @param int $mode                创建权限
     * @return bool                    是否创建成功
     */
    function checkDirAndMk($dirname,$mk=false,$mode=0777){
        if ( is_dir($dirname)==true ){
            return true;
        }
        else {
            if ($mk==false){
                return false;
            }
            else {
                $dirpath_a = explode('/',$dirname);
                for ($i=0;$i<count($dirpath_a);$i++){
                    if ( $dirpath_a[$i]=="" ){
                        continue;
                    }
                    if ( $path==""||is_dir($path) ){
                        if ( $path=="" ){
                            if ( substr(PHP_OS, 0, 3)=="WIN" ){
                                $path = $dirpath_a[$i];
                            }
                            else {
                                $path .= "/".$dirpath_a[$i];
                            }
                        }
                        else {
                            $path .= "/".$dirpath_a[$i];
                        }
                        if ( is_dir($path) ){
                            continue;
                        }
                        else {
                            @mkdir($path,$mode);
                        }
                    }
                    else {
                        return false;
                    }
                }
                return true;
            }
        }
    }
}

$z = new Zip;
$lst=$z->get_list('test2.zip');
foreach ($lst as $val){
    print_r($val)."\n";
}
$zip_obj = new zipPeter();
//$zip_obj->Extract()
$z->Extract('test2.zip', "f:/wytddd", -1 );
/***/

require_once("zip.lib.php");
set_time_limit(100);
//要解压的文件路径
$arch = $_GET["arch"];
if(!$arch || !file_exists($arch))
$z = new Zip;
$l=$z->get_list($arch); //得到文件列表
$z->Extract($arch, "jieya", -1 );
}

(0)

相关推荐

  • php获取文件类型和文件信息的方法

    本文实例讲述了php获取文件类型和文件信息的方法.分享给大家供大家参考.具体实现方法如下: <?php $file = "php.txt"; //打开文件,r表示以只读方式打开 $handle = fopen($file,"r"); //获取文件的统计信息 $fstat = fstat($handle); echo "文件名:".basename($file)."<br>"; //echo "文件大

  • PHP SPL标准库之文件操作(SplFileInfo和SplFileObject)实例

    PHP SPL中提供了SplFileInfo和SplFileObject两个类来处理文件操作. SplFileInfo用来获取文件详细信息: 复制代码 代码如下: $file = new SplFileInfo('foo-bar.txt');   print_r(array(     'getATime' => $file->getATime(), //最后访问时间     'getBasename' => $file->getBasename(), //获取无路径的basenam

  • PHP编程文件处理类SplFileObject和SplFileInfo用法实例分析

    本文实例讲述了PHP编程文件处理类SplFileObject和SplFileInfo用法.分享给大家供大家参考,具体如下: php对于大文件的处理除了用以下方法外还可以直接调用linux命令 文件处理类: SplFileInfo { /* 方法 */ public __construct ( string $file_name ) public int getATime ( void ) //获取文件的最后访问时间 public string getBasename ([ string $suf

  • php实现的支持断点续传的文件下载类

    本文实例讲述了php实现的支持断点续传的文件下载类及其用法,是非常实用的技巧.分享给大家供大家参考.具体方法如下: 通常来说,php支持断点续传,主要依靠HTTP协议中 header HTTP_RANGE实现. HTTP断点续传原理: Http头 Range.Content-Range() HTTP头中一般断点下载时才用到Range和Content-Range实体头, Range用户请求头中,指定第一个字节的位置和最后一个字节的位置,如(Range:200-300) Content-Range用

  • PHP 文件类型判断代码

    何为MIME类型,它是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问时,浏览器会自动使用指定应用程序来打开. 多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式. 参考链接:php文件格式(mime类型)对照表 . 1.mime_content_type()函数判断获取mime类型 mime_content_type返回指定文件的MIME类型,用法: echo mime_content_type ( 'php.gif' ) . "\n" ; echo

  • php下载远程文件类(支持断点续传)

    简易使用方法:  复制代码 代码如下: $object = new httpdownload(); $object->set_byfile($file)%N#H#%;//服务器文件名,包括路径 $object->filename = $filename;//下载另存为的文件名 $object->download(); 3.源文件: 复制代码 代码如下: <? class httpdownload { var $data = null; var $data_len = 0; var

  • PHP文件下载类

    复制代码 代码如下: <?    //====================================================    //   使用范例:    // $download=new download('php,exe,html',false);    //  if(!$download->downloadfile($filename))    //  {    //    echo $download->geterrormsg();    //  }    

  • 一个经典的PHP文件上传类分享

    文件上传是项目开发中比较常见的功能,但文件上传的过程比较繁琐,只要是有文件上传的地方就需要编写这些复杂的代码.为了能在每次开发中降低功能的编写难度,也为了能节省开发时间,通常我们都会将这些反复使用的一段代码封装到一个类中.帮助开发者在以后的开发中,通过编写几条简单代码就可以实现复杂的文件上传功能.对于基础薄弱的读者,只要会使用本类即可,而对一些喜欢挑战的朋友,可以尝试去读懂它,并能开发一个属于自己的文件上传类. 一.需求分析 要球自定义文件上传类,即在使用非常简便的前提下,又可以完成以下几项功能

  • PHP遍历文件夹与文件类及处理类用法实例

    本文实例讲述了PHP遍历文件夹与文件类及处理类用法,非常具有实用价值.分享给大家供大家参考.具体方法如下: FindFile.class.php类文件用于遍历目录文件,具体代码如下: <?php /** 遍历文件夹及文件类 * Date: 2013-03-21 * Author: fdipzone * Ver: 1.0 */ class FindFile{ public $files = array(); // 存储遍历的文件 protected $maxdepth; // 搜寻深度,0表示没有

  • php实现获取文件mime类型的方法

    本文实例讲述了php获取文件mime类型的方法.分享给大家供大家参考.具体如下: 1.使用 mime_content_type 方法 string mime_content_type ( string $filename ) Returns the MIME content type for a file as determined by using information from the magic.mime file. <?php $mime_type = mime_content_typ

  • thinkphp文件处理类Dir.class.php的用法分析

    本文实例分析了thinkphp文件处理类Dir.class.php的用法.分享给大家供大家参考.具体分析如下: 在我的WBlog中,有个清除缓存工能,所谓清除缓存就是删除程序运行时生成的缓存文件,这些文件全部都存在项目的Runtime文件夹里面,当时在做这个清除缓存的程序时使用项目函数库自定义的一个函数来删除缓存文件,只能整个地删除Runtime,太粗糙了,我觉得有必要作一下细分删除,其实thinkphp扩展类库有个不错的文件处理类Dir.class.php,Dir.class.php类,不是每

  • php限制上传文件类型并保存上传文件的方法

    本文实例讲述了php限制上传文件类型并保存上传文件的方法.分享给大家供大家参考.具体如下: 下面的代码演示了php中如何获取用户上传的文件,并限制文件类型的一般图片文件,最后保存到服务器 <?php $allowedExts = array("gif", "jpeg", "jpg", "png"); $extension = end(explode(".", $_FILES["file&qu

随机推荐