日期:2014-05-17  浏览次数:20347 次

php关于zip的使用
/**
	 * 
	 * 创建压缩包
	 * @param array $arr 需要压缩的文件部分路径和文件名,形如 array(
	 *   '/file/upload/1.php',
	 *   '/file/upload/2011/1.jpg',
	 * )
	 * 
	 * @return string 压缩包的部分路径和文件名,形如/file/uplaod/zip/123.zip
	 */
	public static function zip($arr)
	{
	    //首先我建立一个目录
	    $save_path = '/file/upload/zip' . Dat::getHourPath();
	    $path = APPLICATION_PATH . '/destoon' . $save_path;
	    Sys::createDir($path);
	    
	    $zipname = strval(time()) . mt_rand(100000, 999999) . '.zip';
	    $zip_fullname = $path . '/' . $zipname;
	    $zip_obj = new ZipArchive();
        if ($zip_obj->open($zip_fullname, ZIPARCHIVE::CREATE) !== true) { 
            return false; 
        } 
        foreach ($arr as $value) { 
        //  $zip->addFile($path, mb_convert_encoding ( basename($path), 'GBK'  ,'UTF-8')); 
            $zip_obj->addFile( APPLICATION_PATH . '/destoon' . $value, basename($value) ); 
        } 
        $zip_obj->close();
        return $save_path . '/' . $zipname;
	    
	}
	
	/**
	 * 解压缩
	 * 
	 * @param string $zipname 压缩包的部分路径和文件名,形如'/file/upload/1.zip'
	 * @param string $path 解压后的文件夹全路径
	 * 
     * @return array 解压后的文件数组,部分路径和文件名,形如array(
     *     '/file/1.php',
     *     '/file/12.png',
     * )
	 */
	public static function unzip($zipname , $path='')
	{
	    if (!$path ) {
	        $path = '/file/tempzip_folder/' .
               strval(time()) . mt_rand(100000, 999999);
	    
            $newpath = APPLICATION_PATH . '/destoon' . $path; 
	    }
	    else {
	        $newpath = $path;
	        $path = preg_replace('#^.+/destoon(.+)$#', '$1', $newpath);
	    }
	    
        Sys::createDir($newpath);
            
        $filename = APPLICATION_PATH . '/destoon' . $zipname;
        //第一件事是解压
        $zip = new ZipArchive();
        $arr = array();
        if ($zip->open($filename) === true) {
            $zip->extractTo($newpath);
            $zip->close();
            
            $temp = scandir($newpath);
            foreach ($temp as $value) {
                if ($value != '.' && $value != '..') {
                    $arr[] = $path . '/' . basename($value);
                }
            }
        }
        return $arr;
	    
	}