1. 程式人生 > >php下載zip檔案到本地

php下載zip檔案到本地

看程式碼

/**
 * 功能:壓縮檔案並下載函式
 * files: 需要壓縮的檔案,destination:壓縮包名,overwrite:是否使用覆蓋建立
 * 注意:要求php5.0+  zip擴充套件1.7.0+
 */
function create_zip($files = array(),$destination = '',$overwrite = false) {
	//判斷資料夾是否已存在且覆蓋建立為否
	if(file_exists($destination) && !$overwrite) { 
		return false; 
	}

	$valid_files = array();
	//安全處理
	if(is_array($files)) {
		foreach($files as $file) {
			//確認檔案是否存在
			if(file_exists($file)) {
				$valid_files[] = $file;
			}
		}
	}
	//得到要壓縮的檔案後
	if(count($valid_files)) {
		//使用zip函式,如果zip已存在就覆蓋開啟,不存在就建立開啟
		$zip = new ZipArchive();
		if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}
		//向zip資料夾中追加壓縮檔案
		foreach($valid_files as $file) {
			//addFile(檔案絕對路徑,新檔名)
			$zip->addFile($file,$file);
		}
		
		//關閉zip函式
		$zip->close();
		//下載前判斷檔案是否打包
        if(!file_exists($destination)){
            message('資料夾不存在', '', 'error');
        }

        //下載zip
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($destination)); //檔名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告訴瀏覽器,這是二進位制檔案
        header('Content-Length: '. filesize($destination)); //告訴瀏覽器,檔案大小
        readfile($destination);
       	exit();
	}else{
		return false;
	}
}