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;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章