PHP-将某一目录下文件压缩成zip格式

//Start to compress files
$zipfiles = listFileName('./','txt');
$zipfile  = '/test.zip';
create_zip($zipfiles, $zipfile, true);
foreach($zipfiles as $file){
    unlink($file);//不能直接在create_zip方法中删除文件,因为当时正在压缩
}
/**
 * @brief create_zip 
 * Multiple files compressed into a zip format
 *
 * @param array  $files          wait for compressed files. Advice into relative path -> './test.log',
 *                                otherwise file path will similar to the compressed files path
 * @param string $destination    compressed file -> save path
 * @param bool   $overwrite      default:true . if it's seted true and the file exists,it will overwrite
 *
 * @return bool
 */ 
function create_zip($files = array(),$destination = '',$overwrite = false) {  
    //if the zip file already exists and overwrite is false, return false  
    if(file_exists($destination) && !$overwrite) { 
        return false; 
    }  
    $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 file exists,overwrite,else,create 
        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));  
        }  
        $zip->close();  
        //check to make sure the file exists  
        return file_exists($destination);  
    }else{  
        return false;  
    }  
}  

/**
 * @brief listFileName 
 * Rated R lists all the file name
 *
 * @param string $dir       dirname
 * @param string $extension only the file extension will save 
 *
 * @return array
 */ 
function listFileName($dir,$extension){
    static $filename = array();
    if(is_dir($dir)){
        $files = scandir($dir);
        foreach($files as $file){
            if(!in_array($file,array('.','..'))){
                $file_dir = $dir.'/'.$file;
                listFileName($file_dir,$extension);
            }
        }
    }else{
        $path_parts = pathinfo($dir);
        if($path_parts['extension'] == $extension){
            $filename[] = $dir;
        }
    }
    return $filename;
}

 


 

posted on 2014-04-04 14:30  糖果不吃糖  阅读(549)  评论(0编辑  收藏  举报

导航