<?php
function folderToZip ( $folder , & $zipFile , $subfolder = null ) {
if ( $zipFile == null ) {
// no resource given, exit
return false ;
}
// we check if $folder has a slash at its end, if not, we append one
$folder .= end ( str_split ( $folder )) == "/" ? "" : "/" ;
$subfolder .= end ( str_split ( $subfolder )) == "/" ? "" : "/" ;
// we start by going through all files in $folder
$handle = opendir ( $folder );
while ( $f = readdir ( $handle )) {
if ( $f != "." && $f != ".." ) {
if ( is_file ( $folder . $f )) {
// if we find a file, store it
// if we have a subfolder, store it there
if ( $subfolder != null )
$zipFile -> addFile ( $folder . $f , $subfolder . $f );
else
$zipFile -> addFile ( $folder . $f );
} elseif ( is_dir ( $folder . $f )) {
// if we find a folder, create a folder in the zip
$zipFile -> addEmptyDir ( $f );
// and call the function again
folderToZip ( $folder . $f , $zipFile , $f );
}
}
}
}
?>
用法:
<?php
$z = new ZipArchive ();
$z -> open ( "test.zip" , ZIPARCHIVE :: CREATE );
folderToZip ( "storeThisFolder" , $z );
function folderToZip ( $folder , & $zipFile , $subfolder = null ) {
if ( $zipFile == null ) {
// no resource given, exit
return false ;
}
// we check if $folder has a slash at its end, if not, we append one
$folder .= end ( str_split ( $folder )) == "/" ? "" : "/" ;
$subfolder .= end ( str_split ( $subfolder )) == "/" ? "" : "/" ;
// we start by going through all files in $folder
$handle = opendir ( $folder );
while ( $f = readdir ( $handle )) {
if ( $f != "." && $f != ".." ) {
if ( is_file ( $folder . $f )) {
// if we find a file, store it
// if we have a subfolder, store it there
if ( $subfolder != null )
$zipFile -> addFile ( $folder . $f , $subfolder . $f );
else
$zipFile -> addFile ( $folder . $f );
} elseif ( is_dir ( $folder . $f )) {
// if we find a folder, create a folder in the zip
$zipFile -> addEmptyDir ( $f );
// and call the function again
folderToZip ( $folder . $f , $zipFile , $f );
}
}
}
}
?>
用法:
<?php
$z = new ZipArchive ();
$z -> open ( "test.zip" , ZIPARCHIVE :: CREATE );
folderToZip ( "storeThisFolder" , $z );
$z->close();
//设置打包完自动下载
$zipname = "test.zip";
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
//解压缩
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}