PHP用自带的ZipArchive这个类进行压缩文件夹

<?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 );

$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';
}

?>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值