
Nick Lavrov - 2009-07-11 19:30:09
I optimized this package to compact script, 76 lines. all want you need:
zip_file("test123/", "test.zip")
directory "test123/" has been zipped to test.zip archive.
----------------------------------------
<?php #optimized package "create zip". usage: zip_dir("folder","archive_name.zip").
function zip_dir($dname,$zfile) {
$odir="./";
$cdir=array();
$cdata=array();
$oldOffset=0;
$newOffset=0;
if(!is_dir($dname)) trigger_error("zip_dir: Error! Could not locate the specified directory {$dname}",E_USER_ERROR);
#parsing input dir
$tmp=z_parse_dir($dname);
$count=count($tmp);
$ld=strlen($odir);
$cdata[]="\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00".
pack("V",0).pack("V",0).pack("V",0).pack("v",$ld).
pack("v",0).$odir.pack("V",0).pack("V",0).pack("V",0);
$newOffset=strlen(implode("",$cdata));
#root
$cdir[]="\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00".
pack("V",0).pack("V",0).pack("V",0).pack("v",$ld).
pack("v",0).pack("v",0).pack("v",0).pack("v",0).
pack("V",16).pack("V",$oldOffset).$odir;
$oldOffset=$newOffset;
#collect data
for($i=0;$i<$count;$i++){
$fzip=trim($tmp[$i]);
$ndir=substr($fzip,0,(strrpos($fzip,'/')+1));
$odir=$odir.$ndir;
$fc=file_get_contents($fzip);
#---------------------------------------------------------------
#compress file content
$ulen=strlen($fc); #uncompressed length
$compression=crc32($fc);
$gzdata=gzcompress($fc); #file content
$gzdata=substr(substr($gzdata,0,strlen($gzdata)-4),2);
$clen=strlen($gzdata); #compressed length
$cdata[]="\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00\x00\x00\x00\x00".
pack("V",$compression).pack("V",$clen).pack("V",$ulen).
pack("v",strlen($fzip)).pack("v",0).$fzip.$gzdata.pack("V",$compression).
pack("V",$clen).pack("V",$ulen);
$newOffset=strlen(implode("",$cdata));
$cdir[]="\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00\x00\x00\x00\x00".
pack("V",$compression).pack("V",$clen).pack("V",$ulen).
pack("v",strlen($fzip)).pack("v",0).pack("v",0).pack("v",0).pack("v",0).
pack("V",32).pack("V",$oldOffset).$fzip;
$oldOffset=$newOffset;
}
#store to file
$data=implode("",$cdata);
$dir=implode("",$cdir);
$z=fopen($zfile,"wb");
fputs($z,$data.$dir."\x50\x4b\x05\x06\x00\x00\x00\x00".
pack("v",sizeof($cdir)).pack("v",sizeof($cdir)).
pack("V",strlen($dir)).pack("V",strlen($data))."\x00\x00");
fclose($z);
}
#recursive parsing input dir
function z_parse_dir($rpath){
$f=array();
$h=opendir($rpath);
while(($file=@readdir($h))!==false) {
if($file=='.'||$file=='..') continue;
if(is_dir($rpath."/".$file)){
$a=z_parse_dir($rpath."/".$file);
$f=array_merge($a,$f);
}
else $f[]=$rpath."/".$file;
}
return($f);
}
?>
--------------------------------