php 压缩服务器上的文件为zip 和下载zip文件

首先要确保你php.ini    =》extension=php_zip.dll打开


/*  @creates a compressed zip file  将多个文件压缩成一个zip文件的函数 
*   @$files 数组类型  实例array("1.jpg","2.jpg");   
*   @destination  目标文件的路径  如"c:/androidyue.zip" 
*   @$overwrite 是否为覆盖与目标文件相同的文件 
*   @Recorded By Androidyue 
*   @Blog:http://thinkblog.sinaapp.com 
 */  
function create_zip($files = array(),$destination = '',$overwrite = false) {  
    //if the zip file already exists and overwrite is false, return false  
    //如果zip文件已经存在并且设置为不重写返回false  
    if(file_exists($destination) && !$overwrite) { return false; }  
    //vars  
    $valid_files = array();  
    //if files were passed in...  
    //获取到真实有效的文件名  
    if(is_array($files)) {  
        //cycle through each file  
        foreach($files as $file) {  
        //make sure the file exists  
            if(file_exists($file)) {  
            $valid_files[] = $file;  
            }  
        }  
    }  
    //if we have good files...  
    //如果存在真实有效的文件  
    if(count($valid_files)) {  
        //create the archive  
        $zip = new ZipArchive();  
        //打开文件       如果文件已经存在则覆盖,如果没有则创建  
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {  
            return false;  
        }  
        //add the files  
        //向压缩文件中添加文件  
        foreach($valid_files as $file) {  
            $zip->addFile($file,basename($file));  //第一个参数是去取得路劲  第二个参数是压缩文件里的名字
        }  
        //debug  
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;  
        //close the zip -- done!  
        //关闭文件  
        $zip->close();  
        //check to make sure the file exists  
        //检测文件是否存在  
        return file_exists($destination);  
    }else{  
        //如果没有真实有效的文件返回false  
        return false;  
    }  
}  


//测试函数 
$files=array('small/3.jpg'); 
create_zip($files, 'D:/wamp/www/tomedclinic2/aaaaaaa.zip', true); 


下面是下载zip文件

header ( "Cache-Control: max-age=0" );
header ( "Content-Description: File Transfer" );
header ( 'Content-disposition: attachment; filename=叶先生.zip' ); // 文件名
header ( "Content-Type: application/zip" ); // zip格式的
header ( "Content-Transfer-Encoding: binary" ); // 告诉浏览器,这是二进制文件
header ( 'Content-Length: ' . filesize ( 'small/3.jpg' ) ); // 告诉浏览器,文件大小
@readfile ( 'small/3.jpg' );//输出文件;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值