PHP擴充套件類ZipArchive實現壓縮解壓Zip檔案和檔案打包下載
一、解壓縮zip檔案
二、將檔案壓縮成zip檔案$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檔案 }
$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(); }
如果新增的檔案跟PHP檔案不是在同一路徑下,addFile函式的引數如果帶有路徑,則壓縮的檔案裡包含的是帶有路徑的檔案壓縮,而又不希望帶有路徑,則需要該函式的第二個引數
$zip->addFile("images/image.txt","image.txt");
三、檔案追加內容新增到zip檔案
$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'; }
四、將資料夾打包成zip檔案
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檔案
}
五、ZipArchive方法如下:
- ZipArchive::addFile — Adds a file to a ZIP archive from the given path
- ZipArchive::addFromString — Add a file to a ZIP archive using its contents
- ZipArchive::addGlob — Add files from a directory by glob pattern
- ZipArchive::addPattern — Add files from a directory by PCRE pattern
- ZipArchive::close — Close the active archive (opened or newly created)
- ZipArchive::deleteIndex — delete an entry in the archive using its index
- ZipArchive::deleteName — delete an entry in the archive using its name
- ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
- ZipArchive::getCommentName — Returns the comment of an entry using the entry name
- ZipArchive::getFromIndex — Returns the entry contents using its index
- ZipArchive::getFromName — Returns the entry contents using its name
- ZipArchive::getNameIndex — Returns the name of an entry using its index
- ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
- ZipArchive::getStream — Get a file handler to the entry defined by its name (read only).
- ZipArchive::locateName — Returns the index of the entry in the archive
- ZipArchive::setCommentName — Set the comment of an entry defined by its name
- ZipArchive::statIndex — Get the details of an entry defined by its index.
- ZipArchive::statName — Get the details of an entry defined by its name.
- ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
- ZipArchive::unchangeName — Revert all changes done to an entry with the given name.
<?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壓縮檔案並下載打包好的檔案
總結:
- 計算檔案的大小的時候,並不需要先開啟檔案,通過filesize($filename)就可以看出,如果需要先開啟檔案的話,filesize可能就會是這樣的形式了filesize($filehandle)
- 向客戶端回送資料的是,記得要設定一個buffer,用來指定每次向客戶端輸出多少資料,如:$buffer=1023。如果不指定的話,就會將整個檔案全部寫入記憶體當中,再一次性的講資料傳送給客戶端
- 通過feof()函式,可以判斷要讀取的檔案是否讀完,如果還沒讀完,繼續讀取檔案($file_data=fread()),並將資料回送給客戶端(echo $file_data)
- 每次下載完成後,在客戶端都會重新整理下,說明了,其實每次都將資料寫入到一個臨時檔案中,等全部下載完成後,再將所有的資料重新整合在一起
- 這裡我使用的是絕對路徑,絕對路徑有個好處,就是適應性比較強,而且相對於相對路徑,效率更高(免去了查詢檔案的過程)
分析下技術要點:
- 將檔案打包成zip格式
- 下載檔案的功能
要點解析:
- 這裡我採用的是php自帶的ZipArchive類
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>
引用地址:http://my.oschina.net/junn/blog/104464