php 文件压缩zip扩展

<?php


    function addFileToZip($path, $zip)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {//文件夹文件名字为'.'和‘..’,不要对他们进行操作
                if (is_dir($path . "/" . $filename)) {// 如果读取的某个对象是文件夹,则递归
                    addFileToZip($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
                }
            }
        }
        @closedir($path);
    }


    $zip = new ZipArchive();

    $file=date("YMD").".zip";
    fopen($file,'w');//在windows环境下可以省略这句,但是在liunx环境下最好加上,因在有的liunx环境下ZipArchive::CREATE
方法无法自动创建文件,会导致文件压缩失败。

if ($zip->open($file, ZipArchive::CREATE) ===TRUE) { if(file_exists($file)) { addFileToZip('test', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法 }else{ echo "文件不存在"; } //关闭处理的zip文件 if($zip->close()){ return true; }else{ return false; } } else { echo "失败"; }

  

posted @ 2017-03-09 17:43  Window2016  阅读(284)  评论(0编辑  收藏  举报