PHP中ZIP压缩的类 直接操作系统底层

PHP中ZIP压缩的类 直接操作系统底层
具体源码看下面!

<?php
/*------------------------------------------------------------
* Project: WebKey3
* Description: 压缩文件操作类,可以压缩和解压缩ZIP文件。
* Author: 刘春福
* $Id: zip.lib.php,v 1.2 2004/09/22 03:25:24 lcf Exp $
*------------------------------------------------------------*/</code><code>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-&gt;ReadCentralDir($zip,$zip_name);

@rewind($zip);
@fseek($zip, $centd[’offset’]);

for ($i=0; $i&lt;$centd['entries']; $i++)
{
$header = $this-&gt;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’]==0×41FF0010||$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;isset($files[$i]);$i++)
{
$fn = $files[$i];
if(!in_Array(dirname($fn[0]),$this-&gt;dirs))
$this-&gt;add_Dir(dirname($fn[0]));
if(basename($fn[0]))
$ret[basename($fn[0])]=$this-&gt;add_File($fn[1],$fn[0],$compact);
}
return $ret;
}

function get_file()
{
$data = implode(”, $this -&gt; datasec);
$ctrldir = implode(”, $this -&gt; ctrl_dir);

return $data . $ctrldir . $this -&gt; eof_ctrl_dir .
pack(’v', sizeof($this -&gt; ctrl_dir)).pack(’v', sizeof($this -&gt; 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 -&gt; datasec[] = $fr;

$new_offset = strlen(implode(”", $this-&gt;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 -&gt; old_offset ).$name;

$this -&gt; ctrl_dir[] = $cdrec;
$this -&gt; old_offset = $new_offset;
$this -&gt; dirs[] = $name;
}

function add_File($data, $name, $compact = 1)
{
$name = str_replace(’\\’, ‘/’, $name);
$dtime = dechex($this-&gt;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 -&gt; datasec[] = $fr;
$new_offset = strlen(implode(”, $this-&gt;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 -&gt; old_offset );

$this -&gt; old_offset = $new_offset;
$cdrec .= $name;
$this -&gt; ctrl_dir[] = $cdrec;
return true;
}

function DosTime()
{
$timearray = getdate();
if ($timearray[’year’] &lt; 1980)
{
$timearray['year'] = 1980;
$timearray['mon'] = 1;
$timearray['mday'] = 1;
$timearray['hours'] = 0;
$timearray['minutes'] = 0;
$timearray['seconds'] = 0;
}
return (($timearray['year'] - 1980) &lt;&lt; 25) | ($timearray['mon'] &lt;&lt; 21) | ($timearray['mday'] &lt;&lt; 16) | ($timearray['hours'] &lt;&lt; 11) |
($timearray['minutes'] &lt;&lt; 5) | ($timearray['seconds'] &gt;&gt; 1);
}

function Extract ( $zn, $to, $index = Array(-1) )
{
$ok = 0; $zip = @fopen($zn,’rb’);
if(!$zip) return(-1);
$cdir = $this-&gt;ReadCentralDir($zip,$zn);
$pos_entry = $cdir[’offset’];

if(!is_array($index)){ $index = array($index); }
for($i=0;isset($index[$i]);$i++)
{
if(intval($index[$i])!=$index[$i]||$index[$i]&gt;$cdir[’entries’])
return(-1);
}

for ($i=0; $i&lt;$cdir['entries']; $i++)
{
@fseek($zip, $pos_entry);
$header = $this-&gt;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-&gt;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’] &amp;&amp; $header[’mtime’])
{
$hour=($header[’mtime’]&amp;0xF800)&gt;&gt;11;$minute=($header[’mtime’]&amp;0×07E0)&gt;&gt;5;
$seconde=($header[’mtime’]&amp;0×001F)*2;$year=(($header[’mdate’]&amp;0xFE00)&gt;&gt;9)+1980;
$month=($header[’mdate’]&amp;0×01E0)&gt;&gt;5;$day=$header[’mdate’]&amp;0×001F;
$header[’mtime’] = mktime($hour, $minute, $seconde, $month, $day, $year);
}
else $header[’mtime’] = time();

$header[’stored_filename’] = $header[’filename’];
if (substr($header[’filename’], -1) == ‘/’)
$header[’external’] = 0×41FF0010;
else $header[’external’] = 0×0;

$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’] &amp;&amp; $header[’mtime’])
{
$hour = ($header[’mtime’] &amp; 0xF800) &gt;&gt; 11;
$minute = ($header[’mtime’] &amp; 0×07E0) &gt;&gt; 5;
$seconde = ($header[’mtime’] &amp; 0×001F)*2;
$year = (($header[’mdate’] &amp; 0xFE00) &gt;&gt; 9) + 1980;
$month = ($header[’mdate’] &amp; 0×01E0) &gt;&gt; 5;
$day = $header[’mdate’] &amp; 0×001F;
$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’] = 0×41FF0010;
else $header[’external’] = 0×0;
return $header;
}

function ReadCentralDir($zip,$zip_name)
{
$size = filesize($zip_name);
if ($size &lt; 277) $maximum_size = $size;
else $maximum_size=277;

@fseek($zip, $size-$maximum_size);
$pos = ftell($zip); $bytes = 0x00000000;

while ($pos &lt; $size)
{
$byte = @fread($zip, 1); $bytes=($bytes &lt;&lt; | 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-&gt;readfileheader($zip);

if(substr($to,-1)!=”/”) $to.=”/”;
if(!@is_dir($to)) @mkdir($to,0777);

$pth = explode(”/”,dirname($header[’filename’]));
$sAllPathName = $to;
for($i=0;isset($pth[$i]);$i++)
{
if(!$pth[$i]) continue;
$sAllPathName .= $pth[$i].”/”;
if(!is_dir($sAllPathName)) @mkdir($sAllPathName,0777);
}
if (!($header[’external’]==0×41FF0010)&amp;&amp;!($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 &lt; 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 &lt; 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("Can not open the archive file!");
if(!$gzp) return(-2);
$fp = @fopen($to.$header['filename'],'wb');
if(!$fp) return(-1);
$size = $header['size'];

while ($size != 0)
{
$read_size = ($size &lt; 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;
}

//增加文件
function AddFile($sFileName, $compact = 1)
{
if (!file_exists($sFileName)) return false;
else
{
$fd = fopen ($sFileName, "rb");
$contents = fread ($fd, filesize($sFileName));
fclose ($fd);
}
//echo $sFileName;
$aFiles = Array(Array(basename($sFileName),$contents));
return $this-&gt;Add($aFiles,$compact);
}
//增加一个目录下的所有文件和子目录
function AddDir($sRootDir,$compact = 1,$sSubDir=”")
{
if ((substr($sRootDir,-1) != “/”) &amp;&amp; (substr($sRootDir,-1) != “\\”)) $sRootDir .= “/”;
if (($sSubDir != “”) &amp;&amp; (substr($sSubDir,-1) != “/”) &amp;&amp; (substr($sSubDir,-1) != “\\”)) $sSubDir .= “/”;

$handle = @opendir($sRootDir . $sSubDir);
while ($tName = readdir($handle))
{
if (($tName == “.”) ||($tName == “..”)) continue;
if (is_dir($sRootDir . $sSubDir . $tName)) $this-&gt;AddDir($sRootDir,$compact, $sSubDir . $tName . “/”);
else
{
$fd = fopen ($sRootDir . $sSubDir . $tName, “rb”);
$contents = fread ($fd, filesize($sRootDir . $sSubDir . $tName));
fclose ($fd);
$aFiles = Array(Array($sSubDir . $tName,$contents));
$this-&gt;Add($aFiles,$compact);
}
}
closedir($handle);
}
}
/*
增加一个文件
$z = new Zip;
$z-&gt;AddFile(”the/file.name”,1);

增加一个目录
$z = new Zip;
$z-&gt;AddDir(”the/dir/name”,1);

解压缩
$z = new Zip;
$z-&gt;Extract(”styles.zip”,”testzip”);
*/
?>

关注微信公众号,手机阅读更方便: 程序员的阅微草堂

知识共享许可协议莿鸟栖草堂CFC4N 创作,采用 知识共享 署名-非商业性使用-相同方式共享(3.0未本地化版本)许可协议进行许可。基于http://www.cnxct.com上的作品创作。转载请注明转自:PHP中ZIP压缩的类 直接操作系统底层

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据