PHP擴展類ZipArchive實現壓縮解壓Zip文件和文件打包下載
http://my.oschina.net/junn/blog/104464
PHP ZipArchive 是PHP自帶的擴展類,可以輕松實現ZIP文件的壓縮和解壓,使用前首先要確保PHP ZIP 擴展已經開啟,具體開啟方法就不說了,不同的平台開啟PHP擴增的方法網上都有,如有疑問歡迎交流。這里整理一下常用的示例供參考。
一、解壓縮zip文件
|
1
2
3
4
5
6
7
8
9
10
11
|
$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文件
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
$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();
}
|
三、文件追加內容添加到zip文件
|
1
2
3
4
5
6
7
8
9
|
$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文件
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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::addEmptyDir — Add a new directory
- 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::extractTo — Extract the archive contents
- ZipArchive::getArchiveComment — Returns the Zip archive comment
- 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::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
- ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its 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::open — Open a ZIP file archive
- ZipArchive::renameIndex — Renames an entry defined by its index
- ZipArchive::renameName — Renames an entry defined by its name
- ZipArchive::setArchiveComment — Set the comment of a ZIP archive
- ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
- ZipArchive::setCommentName — Set the comment of an entry defined by its name
- ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
- ZipArchive::setExternalAttributesName — Set the external attributes 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::unchangeAll — Undo all changes done in the archive
- ZipArchive::unchangeArchive — Revert all global changes done in the archive.
- 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文件打包下載zip
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?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壓縮文件並下載打包好的文件
總結:
- 使用PHP下載文件的操作需要給出四個header(),可參考:PHP下載文件名中文亂碼解決方法和PHP下載流程分析
- 計算文件的大小的時候,並不需要先打開文件,通過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()函數,客戶端就知道該如何處理文件,是保存還是打開等等
最終的效果如下圖所示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
<?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'
);
//下載完成后要進行刪除
}
}
}
?>
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
<?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>"
;
}
}
}
?>
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<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>
|

