PHP ZipArchive 是PHP自帶的擴展類,能夠輕鬆實現ZIP文件的壓縮和解壓,使用前首先要確保PHP ZIP 擴展已經開啓,具體開啓方法就不說了,不一樣的平臺開啓PHP擴增的方法網上都有,若有疑問歡迎交流。這裏整理一下經常使用的示例供參考。
1、解壓縮zip文件 javascript
$zip = new ZipArchive;//新建一個ZipArchive的對象 /* 經過ZipArchive的對象處理zip文件 $zip->open這個方法的參數表示處理的zip文件名。 若是對zip文件對象操做成功,$zip->open這個方法會返回TRUE */ if ($zip->open('test.zip') === TRUE) { $zip->extractTo('images');//假設解壓縮到在當前路徑下images文件夾的子文件夾php $zip->close();//關閉處理的zip文件 }
2、將文件壓縮成zip文件 php
$zip = new ZipArchive; /* $zip->open這個方法第一個參數表示處理的zip文件名。 第二個參數表示處理模式,ZipArchive::OVERWRITE表示若是zip文件存在,就覆蓋掉原來的zip文件。 若是參數使用ZIPARCHIVE::CREATE,系統就會往原來的zip文件裏添加內容。 若是不是爲了屢次添加內容到zip文件,建議使用ZipArchive::OVERWRITE。 使用這兩個參數,若是zip文件不存在,系統都會自動新建。 若是對zip文件對象操做成功,$zip->open這個方法會返回TRUE */ if ($zip->open('test.zip', ZipArchive::OVERWRITE) === TRUE) { $zip->addFile('image.txt');//假設加入的文件名是image.txt,在當前路徑下 $zip->close(); }
3、文件追加內容添加到zip文件 html
$zip = new ZipArchive; $res = $zip->open('test.zip', ZipArchive::CREATE); if ($res === TRUE) { $zip->addFromString('test.txt', 'file content goes here'); $zip->close(); echo 'ok'; } else { echo 'failed'; }
4、將文件夾打包成zip文件 java
function addFileToZip($path, $zip) { $handler = opendir($path); //打開當前文件夾由$path指定。 /* 循環的讀取文件夾下的全部文件和文件夾 其中$filename = readdir($handler)是每次循環的時候將讀取的文件名賦值給$filename, 爲了避免陷於死循環,因此還要讓$filename !== false。 必定要用!==,由於若是某個文件名若是叫'0',或者某些被系統認爲是表明false,用!=就會中止循環 */ 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(); if ($zip->open('images.zip', ZipArchive::OVERWRITE) === TRUE) { addFileToZip('images/', $zip); //調用方法,對要打包的根目錄進行操做,並將ZipArchive的對象傳遞給方法 $zip->close(); //關閉處理的zip文件 }
5、ZipArchive方法以下: jquery
另附一:幾行代碼實現PHP文件打包下載zip linux
<?php /** * 沒有寫成class 或者 function ,須要的朋友本身寫,就這麼幾行。。 */ $filename = "./test/test.zip"; //最終生成的文件名(含路徑) if(!file_exists($filename)){ //從新生成文件 $zip = new ZipArchive();//使用本類,linux需開啓zlib,windows需取消php_zip.dll前的註釋 if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { exit('沒法打開文件,或者文件建立失敗'); } foreach( $datalist as $val){ $attachfile = $attachmentDir . $val['filepath']; //獲取原始文件路徑 if(file_exists($attachfile)){ $zip->addFile( $attachfile , basename($attachfile));//第二個參數是放在壓縮包中的文件名稱,若是文件可能會有重複,就須要注意一下 } } $zip->close();//關閉 } if(!file_exists($filename)){ exit("沒法找到文件"); //即便建立,仍有可能失敗。。。。 } header("Cache-Control: public"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename='.basename($filename)); //文件名 header("Content-Type: application/zip"); //zip格式的 header("Content-Transfer-Encoding: binary"); //告訴瀏覽器,這是二進制文件 header('Content-Length: '. filesize($filename)); //告訴瀏覽器,文件大小 @readfile($filename); ?>
另附二:文件打包,下載之使用PHP自帶的ZipArchive壓縮文件並下載打包好的文件 ajax
總結: windows
分析下技術要點:
瀏覽器
要點解析: 服務器
a) 咱們只須要new一個ZipArchive對象,而後使用open方法建立一個zip文件,接着使用addFile方法,將要打包的文件寫入剛剛建立的zip文件中,最好還得記得關閉該對象。
b) 注意點:使用open方法的時候,第二個參數$flags是可選的,$flags用來指定對打開的zip文件的處理方式,共有四種狀況
i. ZIPARCHIVE::OVERWRITE老是建立一個新的文件,若是指定的zip文件存在,則會覆蓋掉
ii. ZIPARCHIVE::CREATE 若是指定的zip文件不存在,則新建一個
iii. ZIPARCHIVE::EXCL 若是指定的zip文件存在,則會報錯
iv. ZIPARCHIVE::CHECKCONS
下載文件的流程:
服務器端的工做:
-------------------------------------------
客戶端的瀏覽器發送一個請求處處理下載的php文件。
注意:任何一個操做都首先須要寫入到內存當中,不論是視頻、音頻仍是文本文件,都須要先寫入到內存當中。
換句話說,將「服務器」上的文件讀入到「服務器」的內存當中的這個操做時必不可少的(注意:這裏我將服務器三個字加上雙引號,主要是說明這一系類的操做時在服務器上完成的)。<br>
既然要將文件寫入到內存當中,就必然要先將文件打開
因此這裏就須要三個文件操做的函數了:
一:fopen($filename ,$mode)
二:fread ( int $handle , int $length )
三:fclose ( resource $handle )
---------------------------------------
客戶端端的工做:
---------------------------------------
那麼,如何將已經存在於服務器端內存當中的文件信息流,傳給客戶端呢?
答案是經過header()函數,客戶端就知道該如何處理文件,是保存仍是打開等等
最終的效果以下圖所示:
<?php require'./download.php'; /** * 遍歷目錄,打包成zip格式 */ class traverseDir{ public $currentdir;//當前目錄 public $filename;//文件名 public $fileinfo;//用於保存當前目錄下的全部文件名和目錄名以及文件大小 public function __construct(){ $this->currentdir=getcwd();//返回當前目錄 } //遍歷目錄 public function scandir($filepath){ if (is_dir($filepath)){ $arr=scandir($filepath); foreach ($arr as $k=>$v){ $this->fileinfo[$v][]=$this->getfilesize($v); } }else { echo "<script>alert('當前目錄不是有效目錄');</script>"; } } /** * 返回文件的大小 * * @param string $filename 文件名 * @return 文件大小(KB) */ public function getfilesize($fname){ return filesize($fname)/1024; } /** * 壓縮文件(zip格式) */ public function tozip($items){ $zip=new ZipArchive(); $zipname=date('YmdHis',time()); if (!file_exists($zipname)){ $zip->open($zipname.'.zip',ZipArchive::OVERWRITE);//建立一個空的zip文件 for ($i=0;$i<count($items);$i++){ $zip->addFile($this->currentdir.'/'.$items[$i],$items[$i]); } $zip->close(); $dw=new download($zipname.'.zip'); //下載文件 $dw->getfiles(); unlink($zipname.'.zip'); //下載完成後要進行刪除 } } } ?>
<?php /** * 下載文件 * */ class download{ protected $_filename; protected $_filepath; protected $_filesize;//文件大小 public function __construct($filename){ $this->_filename=$filename; $this->_filepath=dirname(__FILE__).'/'.$filename; } //獲取文件名 public function getfilename(){ return $this->_filename; } //獲取文件路徑(包含文件名) public function getfilepath(){ return $this->_filepath; } //獲取文件大小 public function getfilesize(){ return $this->_filesize=number_format(filesize($this->_filepath)/(1024*1024),2);//去小數點後兩位 } //下載文件的功能 public function getfiles(){ //檢查文件是否存在 if (file_exists($this->_filepath)){ //打開文件 $file = fopen($this->_filepath,"r"); //返回的文件類型 Header("Content-type: application/octet-stream"); //按照字節大小返回 Header("Accept-Ranges: bytes"); //返回文件的大小 Header("Accept-Length: ".filesize($this->_filepath)); //這裏對客戶端的彈出對話框,對應的文件名 Header("Content-Disposition: attachment; filename=".$this->_filename); //修改以前,一次性將數據傳輸給客戶端 echo fread($file, filesize($this->_filepath)); //修改以後,一次只傳輸1024個字節的數據給客戶端 //向客戶端回送數據 $buffer=1024;// //判斷文件是否讀完 while (!feof($file)) { //將文件讀入內存 $file_data=fread($file,$buffer); //每次向客戶端回送1024個字節的數據 echo $file_data; } fclose($file); }else { echo "<script>alert('對不起,您要下載的文件不存在');</script>"; } } } ?>頁面顯示的代碼:
<script type="text/javascript" src="jquery-1.7.2.js"></script> <script type="text/javascript" src="ajax.js"></script> <?php header("Content-type:text/html;charset=utf8"); require('./getfile.php'); $scandir=new traverseDir(); $scandir->scandir($scandir->currentdir); $scandir->currentdir; if (isset($_POST['down_load'])){ $items=$_POST['items']; $scandir->tozip($items);//將文件壓縮成zip格式 } echo "當前的工做目錄:".$scandir->currentdir; echo "<br>當前目錄下的全部文件"; ?> <form action="list.php" method="POST"> <table> <tr> <td></td> <td>名稱</td> <td>大小(KB)</td> </tr> <?php $res=$scandir->fileinfo; foreach ($res as $k=>$v){ if (!($k=='.' || $k=='..')) {//過濾掉.和.. ?> <tr> <td><input type="checkbox" name="items[]" class="filename" value="<?php echo $k;?>"></td> <td><?php echo $k; ?></td> <td><?php echo number_format($v[0],0); ?></td> </tr> <?php } } ?> <tr> <td><input type="checkbox" id="selall"><label for="selall">全選</label></td> <td><input type="submit" name="down_load" value="打包並下載" id="tozip_tetttt"></td> </tr> </table> </form>