2024 年 PHP Conference Japan

ZipArchive 類別

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

簡介

使用 Zip 壓縮的檔案庫。

類別概要

class ZipArchive implements Countable {
/* 常數 */
public const int CREATE;
public const int EXCL;
公開 常數 整數 CHECKCONS;
公開 常數 整數 OVERWRITE;
公開 常數 整數 RDONLY;
公開 常數 整數 FL_NOCASE;
公開 常數 整數 FL_NODIR;
公開 常數 整數 FL_COMPRESSED;
公開 常數 整數 FL_UNCHANGED;
公開 常數 整數 FL_RECOMPRESS;
公開 常數 整數 FL_ENCRYPTED;
公開 常數 整數 FL_OVERWRITE;
公開 常數 整數 FL_LOCAL;
公開 常數 整數 FL_CENTRAL;
公開 常數 整數 FL_ENC_GUESS;
公開 常數 整數 FL_ENC_RAW;
公開 常數 整數 FL_ENC_STRICT;
公開 常數 整數 FL_ENC_UTF_8;
公開 常數 整數 FL_ENC_CP437;
公開 常數 整數 FL_OPEN_FILE_NOW;
公開 常數 整數 CM_DEFAULT;
公開 常數 整數 CM_STORE;
公開 常數 整數 CM_SHRINK;
公開 常數 整數 CM_REDUCE_1;
公開 常數 整數 CM_REDUCE_2;
公開 常數 整數 CM_REDUCE_3;
公開 常數 整數 CM_REDUCE_4;
公開 常數 整數 CM_IMPLODE;
公開 常數 整數 CM_DEFLATE;
公開 常數 整數 CM_DEFLATE64;
公開 常數 整數 CM_PKWARE_IMPLODE;
公開 常數 整數 CM_BZIP2;
公開 常數 整數 CM_LZMA;
公開 常數 整數 CM_LZMA2;
公開 常數 整數 CM_ZSTD;
公開 常數 整數 CM_XZ;
公開 常數 整數 CM_TERSE;
公開 常數 整數 CM_LZ77;
公開 常數 整數 CM_WAVPACK;
公開 常數 整數 CM_PPMD;
公開 常數 整數 ER_OK;
公開 常數 整數 ER_MULTIDISK;
公開 常數 整數 ER_RENAME;
公開 常數 整數 ER_CLOSE;
公開 常數 整數 ER_SEEK;
公開 常數 整數 ER_READ;
公開 常數 整數 ER_WRITE;
公開 常數 整數 ER_CRC;
公開 常數 整數 ER_ZIPCLOSED;
公開 常數 整數 ER_NOENT;
公開 常數 整數 ER_EXISTS;
公開 常數 整數 ER_OPEN;
公開 常數 整數 ER_TMPOPEN;
公開 常數 整數 ER_ZLIB;
公開 常數 整數 ER_MEMORY;
公開 常數 整數 ER_CHANGED;
公開 常數 整數 ER_COMPNOTSUPP;
公開 常數 整數 ER_EOF;
公開 常數 整數 ER_INVAL;
公開 常數 整數 ER_NOZIP;
公開 常數 整數 ER_INTERNAL;
公開 常數 整數 ER_INCONS;
公開 常數 整數 ER_REMOVE;
公開 常數 整數 ER_DELETED;
公開 常數 整數 ER_ENCRNOTSUPP;
公開 常數 整數 ER_RDONLY;
公開 常數 整數 ER_NOPASSWD;
公開 常數 整數 ER_WRONGPASSWD;
公開 常數 整數 ER_OPNOTSUPP;
公開 常數 整數 ER_INUSE;
公開 常數 整數 ER_TELL;
公開 常數 整數 ER_COMPRESSED_DATA;
公開 常數 整數 ER_CANCELLED;
公開 常數 整數 ER_DATA_LENGTH;
公開 常數 整數 ER_NOT_ALLOWED;
公開 常數 整數 ER_TRUNCATED_ZIP;
公開 常數 整數 AFL_RDONLY;
公開 常數 整數 AFL_IS_TORRENTZIP;
公開 常數 整數 OPSYS_DOS;
公開 常數 整數 OPSYS_AMIGA;
公開 常數 整數 OPSYS_OPENVMS;
公開 常數 整數 OPSYS_UNIX;
公開 常數 整數 OPSYS_VM_CMS;
公開 常數 整數 OPSYS_ATARI_ST;
公開 常數 整數 OPSYS_OS_2;
公開 常數 整數 OPSYS_MACINTOSH;
公開 常數 整數 OPSYS_Z_SYSTEM;
公開 常數 整數 OPSYS_CPM;
公開 常數 整數 OPSYS_WINDOWS_NTFS;
公開 常數 整數 OPSYS_MVS;
公開 常數 整數 OPSYS_VSE;
公開 常數 整數 OPSYS_ACORN_RISC;
公開 常數 整數 OPSYS_VFAT;
公開 常數 整數 OPSYS_BEOS;
公開 常數 整數 OPSYS_TANDEM;
公開 常數 整數 OPSYS_OS_400;
公開 常數 整數 OPSYS_OS_X;
公開 常數 整數 OPSYS_DEFAULT;
公開 常數 整數 EM_NONE;
公開 常數 整數 EM_TRAD_PKWARE;
公開 常數 整數 EM_AES_128;
公開 常數 整數 EM_AES_192;
公開 常數 整數 EM_AES_256;
公開 常數 整數 EM_UNKNOWN;
公開 常數 字串 LIBZIP_VERSION;
公開 常數 整數 LENGTH_TO_END;
公開 常數 整數 LENGTH_UNCHECKED;
/* 屬性 */
公開 唯讀 整數 $lastId;
公開 唯讀 整數 $status;
公開 唯讀 整數 $statusSys;
公開 唯讀 整數 $numFiles;
公開 唯讀 字串 $filename;
公開 唯讀 字串 $comment;
/* 方法 */
公開 新增空目錄(字串 $dirname, 整數 $flags = 0): 布林值
公開 新增檔案(
    字串 $filepath,
    字串 $entryname = "",
    整數 $start = 0,
    整數 $length = ZipArchive::LENGTH_TO_END,
    整數 $flags = ZipArchive::FL_OVERWRITE
): 布林值
公開 從字串新增(字串 $name, 字串 $content, 整數 $flags = ZipArchive::FL_OVERWRITE): 布林值
公開 新增符合萬用字元(字串 $pattern, 整數 $flags = 0, 陣列 $options = []): 陣列|false
公開 addPattern(字串 $pattern, 字串 $path = ".", 陣列 $options = []): 陣列|false
公開 clearError():
公開 close(): 布林值
公開 count(): 整數
公開 deleteIndex(整數 $index): 布林值
公開 deleteName(字串 $name): 布林值
公開 extractTo(字串 $pathto, 陣列|字串|null $files = null): 布林值
公開 getArchiveComment(整數 $flags = 0): 字串|false
公開 getArchiveFlag(整數 $flag, 整數 $flags = 0): 整數
公開 getCommentIndex(整數 $index, 整數 $flags = 0): 字串|false
公開 getCommentName(字串 $name, 整數 $flags = 0): 字串|false
公開 getExternalAttributesIndex(
    整數 $index,
    整數型 &$opsys,
    整數型 &$attr,
    整數型 $flags = 0
): 布林值
公開方法 getExternalAttributesName(
    字串 $name,
    整數型 &$opsys,
    整數型 &$attr,
    整數型 $flags = 0
): 布林值
公開方法 getFromIndex(整數型 $index, 整數型 $len = 0, 整數型 $flags = 0): 字串|布林值
公開方法 getFromName(字串 $name, 整數型 $len = 0, 整數型 $flags = 0): 字串|布林值
公開方法 getNameIndex(整數型 $index, 整數型 $flags = 0): 字串|布林值
公開方法 getStatusString(): 字串
公開方法 getStream(字串 $name): 資源|布林值
公開方法 getStreamIndex(整數型 $index, 整數型 $flags = 0): 資源|布林值
公開 getStreamName(字串 $name, 整數 $flags = 0): 資源|false
公開 locateName(字串 $name, 整數 $flags = 0): 整數|false
公開 open(字串 $filename, 整數 $flags = 0): 布林值|整數
公開 renameIndex(整數 $index, 字串 $new_name): 布林值
公開 重新命名(字串 $name, 字串 $new_name): 布林值
公開 取代檔案( )
    字串 $filepath,
    整數 $index,
    整數 $start = 0,
    整數 $length = ZipArchive::LENGTH_TO_END,
    整數型 $flags = 0
): 布林值
公開 設定註解索引(整數 $index, 字串 $comment): 布林值
公開 設定註解名稱(字串 $name, 字串 $comment): 布林值
公開 設定壓縮索引(整數 $index, 整數 $method, 整數 $compflags = 0): 布林值
公開 設定壓縮名稱(字串 $name, 整數 $method, 整數 $compflags = 0): 布林值
公開 設定外部屬性索引(
    整數 $index,
    整數 $opsys,
    整數 $attr,
    整數型 $flags = 0
): 布林值
公開 設定外部屬性名稱(
    字串 $name,
    整數 $opsys,
    整數 $attr,
    整數型 $flags = 0
): 布林值
公開 設定修改時間索引(整數 $index, 整數 $timestamp, 整數 $flags = 0): 布林值
公開 設定修改時間名稱(字串 $name, 整數 $timestamp, 整數 $flags = 0): 布林值
公開 取得索引狀態(整數 $index, 整數 $flags = 0): 陣列|
公開 取得名稱狀態(字串 $name, 整數 $flags = 0): 陣列|
}

屬性

lastId

最後添加的項目(檔案或目錄)的索引值。從 PHP 8.0.0 和 PECL zip 1.18.0 開始提供。

status

Zip 檔案的狀態。適用於已關閉的檔案,從 PHP 8.0.0 和 PECL zip 1.18.0 開始提供。

statusSys

Zip 檔案的系統狀態。適用於已關閉的檔案,從 PHP 8.0.0 和 PECL zip 1.18.0 開始提供。

numFiles

檔案中的檔案數量

filename

檔案系統中的檔案名稱

comment

檔案的註釋

目錄

新增註記

使用者貢獻的註記 15 則註記

umbalaconmeogia at NOSPAM dot gmail dot com
12 年前
壓縮資料夾(包含自身)。
用法
HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');

<?php
class HZip
{
/**
* Add files and sub-directories in a folder to zip file.
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
*/
private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
$handle = opendir($folder);
while (
false !== $f = readdir($handle)) {
if (
$f != '.' && $f != '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $exclusiveLength);
if (
is_file($filePath)) {
$zipFile->addFile($filePath, $localPath);
} elseif (
is_dir($filePath)) {
// Add sub-directory.
$zipFile->addEmptyDir($localPath);
self::folderToZip($filePath, $zipFile, $exclusiveLength);
}
}
}
closedir($handle);
}

/**
* Zip a folder (include itself).
* Usage:
* HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
*
* @param string $sourcePath Path of directory to be zip.
* @param string $outZipPath Path of output zip file.
*/
public static function zipDir($sourcePath, $outZipPath)
{
$pathInfo = pathInfo($sourcePath);
$parentPath = $pathInfo['dirname'];
$dirName = $pathInfo['basename'];

$z = new ZipArchive();
$z->open($outZipPath, ZIPARCHIVE::CREATE);
$z->addEmptyDir($dirName);
self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
$z->close();
}
}
?>
ohcc at 163 dot com
9 年前
使用 PHP 5.6+ 版本時,您可能會遇到這些錯誤。

警告:未知:無法在第 0 行的未知位置銷毀 zip 上下文

警告:ZipArchive::close():無法移除檔案:在 xxxx.php 的第 xx 行找不到檔案或目錄

範例

警告:未知:無法在第 0 行的未知位置銷毀 zip 上下文

<?php
$za
= new ZipArchive;
$za->open('51-n.com.zip',ZipArchive::CREATE|ZipArchive::OVERWRITE);
?>

警告:ZipArchive::close():無法移除檔案:在 xxxx.php 的第 xx 行找不到檔案或目錄

<?php
$za
= new ZipArchive;
$za->open('51-n.com.zip',ZipArchive::CREATE|ZipArchive::OVERWRITE);
$za->close();
?>

當 zip 壓縮檔為空時會發生這種情況。
您的 zip 壓縮檔除非至少包含一個檔案,否則不會儲存到磁碟。此外,當套用 ZipArchive::OVERWRITE 時,如果存在同名檔案,則在呼叫 ZipArchive::open() 後會將其移除。

因此,別忘了在您的 zip 壓縮檔中至少放入一個檔案。

<?php
$za
= new ZipArchive;
$za->open('51-n.com.zip',ZipArchive::CREATE|ZipArchive::OVERWRITE);
$za->addFromString('wuxiancheng.cn.txt','yes');
$za->close();
?>
theking2(at)king.ma
1 年前
使用 DirectoryIterator 遞迴壓縮資料夾是一種現代的方法。我使用這個小類別

<?php
class MakeZip
{
private
ZipArchive $zipArchive;
private
int $startPathLength; // chars to remove from the start for the stored entity

public function __construct(
string $zipArchivename,
public readonly
string $startPath,
public readonly
mixed $convert_function,
)
{
$this->zipArchive = new \ZipArchive;
$this->zipArchive->open($zipArchivename, ZipArchive::CREATE);
$this->startPathLength = strlen($this-> startPath);

$this-> zipDir($startPath);
}
public function
__destruct()
{
$this-> zipArchive-> close();
}

/**
* Add files and sub-directories in a folder to zip file.
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
*/
private function zipDir($folder)
{
echo
$folder . '<br>' . PHP_EOL;
foreach (new
\DirectoryIterator($folder) as $f) {
if (
$f->isDot())
continue;
//skip . ..
if ($f->isDir()) {
if(
$f->getExtension() === 'git') continue; // skip .git folder
$this-> zipArchive-> addEmptyDir($f->getPathname());
$this-> zipDir($f->getPathname());

continue;
}
if (
$f->isFile()) {
if (
$f->getBasename() === basename(__FILE__)) continue; // skip self
if ($f->getExtension() === 'zip') continue; // skip ZIP files

$this-> zipArchive ->addFile( substr($f-> getPathname(), $this-> startPathLength) ); // remove './'

continue;
}

}
}
}
?>

可以這樣使用
<?php
$host
= str_replace('.', '_', $_SERVER['HTTP_HOST']);
$date = date('Ymd-His');

$zip = new \MakeZip("./archiv-$host-$date.zip", './', $convert_function);
unset(
$zip);
?>

在建構函式中加入加密或其他功能。
AshleyDambra at live dot com
11 年前
簡單的 xZip 類別,可將大型資料夾壓縮成多個部分,並一次解壓縮多個 zip 檔案。

<?php
class xZip {
public function
__construct() {}
private function
_rglobRead($source, &$array = array()) {
if (!
$source || trim($source) == "") {
$source = ".";
}
foreach ((array)
glob($source . "/*/") as $key => $value) {
$this->_rglobRead(str_replace("//", "/", $value), $array);
}

foreach ((array)
glob($source . "*.*") as $key => $value) {
$array[] = str_replace("//", "/", $value);
}
}
private function
_zip($array, $part, $destination) {
$zip = new ZipArchive;
@
mkdir($destination, 0777, true);

if (
$zip->open(str_replace("//", "/", "{$destination}/partz{$part}.zip"), ZipArchive::CREATE)) {
foreach ((array)
$array as $key => $value) {
$zip->addFile($value, str_replace(array("../", "./"), NULL, $value));
}
$zip->close();
}
}
public function
zip($limit = 500, $source = NULL, $destination = "./") {
if (!
$destination || trim($destination) == "") {
$destination = "./";
}

$this->_rglobRead($source, $input);
$maxinput = count($input);
$splitinto = (($maxinput / $limit) > round($maxinput / $limit, 0)) ? round($maxinput / $limit, 0) + 1 : round($maxinput / $limit, 0);

for(
$i = 0; $i < $splitinto; $i ++) {
$this->_zip(array_slice($input, ($i * $limit), $limit, true), $i, $destination);
}

unset(
$input);
return;
}
public function
unzip($source, $destination) {
@
mkdir($destination, 0777, true);

foreach ((array)
glob($source . "/*.zip") as $key => $value) {
$zip = new ZipArchive;
if (
$zip->open(str_replace("//", "/", $value)) === true) {
$zip->extractTo($destination);
$zip->close();
}
}
}

public function
__destruct() {}
}

//$zip = new xZip;
//$zip->zip(500, "images/", "images_zip/");
//$zip->unzip("images_zip/", "images/");
?>
Jerry dot Saravia at emc dot com
13 年前
以下程式碼可用於取得 zip 檔案中所有檔案名稱的清單。

<?php
$za
= new ZipArchive();

$za->open('theZip.zip');

for(
$i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
print_r( basename( $stat['name'] ) . PHP_EOL );
}
?>
ebestwebmaster at gmail dot com
9 年前
壓縮檔案並下載的方法
<?php

$files
= array('image.jpeg','text.txt','music.wav');
$zipname = 'enter_any_name_for_the_zipped_file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach (
$files as $file) {
$zip->addFile($file);
}
$zip->close();

///接著下載壓縮檔。
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

?>
hardcorevenom at gmx dot com
14 年前
從壓縮檔讀取檔案到變數中。
如果 CRC32 檢查碼不符,會自動顯示警告訊息,我們可以捕捉這個警告,以便顯示我們自己的錯誤訊息。

<?php
$zip
= new ZipArchive();
if (
$zip->open('archive.zip')) {
$fp = $zip->getStream('myfile.txt'); // 取得壓縮檔內的檔案
if( !$fp)
die(
"錯誤:無法取得壓縮檔內檔案的串流");
$stat = $zip->statName('myfile.txt');

$buf = ""; // 檔案緩衝區
ob_start(); // 用於擷取 CRC 錯誤訊息
while (!feof($fp)) {
$buf .= fread($fp, 2048); // 讀取超過 2156 位元組似乎會停用內部 CRC32 驗證 (錯誤?)
}
$s = ob_get_contents();
ob_end_clean();
if(
stripos($s, "CRC error") != FALSE){
echo
'CRC32 不符,目前 ';
printf("%08X", crc32($buf)); // 目前 CRC
echo ',預期 ';
printf("%08X", $stat['crc']); // 預期 CRC
}

fclose($fp);
$zip->close();
// 完成,解壓縮的檔案儲存在 $buf 中
}
?>

要建立損壞的檔案,請使用十六進位編輯器更改 zip 檔案中的位元組。
bruno dot vibert at bonobox dot fr
12 年前
有一個好用的函式可以將 ZipArchive 狀態以人類可讀的字串形式取得。

<?php
function ZipStatusString( $status )
{
switch( (int)
$status )
{
case
ZipArchive::ER_OK : return 'N No error';
case
ZipArchive::ER_MULTIDISK : return 'N Multi-disk zip archives not supported';
case
ZipArchive::ER_RENAME : return 'S Renaming temporary file failed';
case
ZipArchive::ER_CLOSE : return 'S Closing zip archive failed';
case
ZipArchive::ER_SEEK : return 'S Seek error';
case
ZipArchive::ER_READ : return 'S Read error';
case
ZipArchive::ER_WRITE : return 'S Write error';
case
ZipArchive::ER_CRC : return 'N CRC error';
case
ZipArchive::ER_ZIPCLOSED : return 'N Containing zip archive was closed';
case
ZipArchive::ER_NOENT : return 'N No such file';
case
ZipArchive::ER_EXISTS : return 'N File already exists';
case
ZipArchive::ER_OPEN : return 'S Can\'t open file';
case
ZipArchive::ER_TMPOPEN : return 'S Failure to create temporary file';
case
ZipArchive::ER_ZLIB : return 'Z Zlib error';
case
ZipArchive::ER_MEMORY : return 'N Malloc failure';
case
ZipArchive::ER_CHANGED : return 'N Entry has been changed';
case
ZipArchive::ER_COMPNOTSUPP : return 'N Compression method not supported';
case
ZipArchive::ER_EOF : return 'N Premature EOF';
case
ZipArchive::ER_INVAL : return 'N Invalid argument';
case
ZipArchive::ER_NOZIP : return 'N Not a zip archive';
case
ZipArchive::ER_INTERNAL : return 'N Internal error';
case
ZipArchive::ER_INCONS : return 'N Zip archive inconsistent';
case
ZipArchive::ER_REMOVE : return 'S Can\'t remove file';
case
ZipArchive::ER_DELETED : return 'N Entry has been deleted';

default: return
sprintf('Unknown status %s', $status );
}
}

?>
webmaster at sebastiangrinke dot info
13 年前
這是一個簡單的函式,可以壓縮包含所有子資料夾的資料夾或只壓縮單個檔案... $data 變數可以是字串或陣列...

<?php
public function un_zip($data,$arcpf,$mode='zip',$obj=''){
$absoluterpfad = 'YOUR_BASE_PATH';
$arcpf = $absoluterpfad.DS.$arcpf;
if(
is_object($obj)==false){
$archiv = new ZipArchive();
$archiv->open($arcpf,ZipArchive::CREATE);
}else{
$archiv =& $obj;}
if(
$mode=='zip'){
if(
is_array($data)==true){
foreach(
$data as $dtmp){
$archiv =& un_zip($dtmp,$arcpf,'zip',&$archiv);
}
}else{
if(
is_dir($data)==true){
$archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data));
$files = scandir($data);
$bad = array('.','..');
$files = array_diff($files,$bad);
foreach(
$files as $ftmp){
if(
is_dir($data.DS.$ftmp)==true){
$archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
$archiv =& un_zip($data.DS.$ftmp,$arcpf,'zip',&$archiv);
}elseif(
is_file($data.DS.$ftmp)==true){
$archiv->addFile($data.DS.$ftmp,str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
}
}
}elseif(
is_file($data)==true){$archiv->addFile($data,str_replace($absoluterpfad.DS,'',$data));}
}
}
if(
is_object($obj)==false){$archiv->close();}
else{return
$archiv;}
if(
$mode=='unzip'){$archiv->extractTo($data);}
}
?>
nick at fullfatthings dot com
9 年前
PHP 5.3.3 中存在限制(似乎在後續版本中已解決;5.3.29 在其他伺服器上似乎正常)。

如果您嘗試開啟包含超過 65,535 個檔案的 zip 檔案(在我的情況下,它有 237,942 個檔案),則您將無法存取後面的檔案。 numFiles 屬性只會回報前 65k 個檔案。
niklas dot schumi at NOSPAM dot googlemail dot com
12 年前
嗨,大家好。
我剛寫了一個小函式,可以在維持目錄結構的同時壓縮整個資料夾。我希望它可以幫助到某些人。

<?php
function folderToZip($folder, &$zipFile, $subfolder = null) {
if (
$zipFile == null) {
// 沒有提供資源,結束執行
return false;
}
// 檢查 $folder 字串結尾是否包含斜線,若無則加上
$folder .= end(str_split($folder)) == "/" ? "" : "/";
$subfolder .= end(str_split($subfolder)) == "/" ? "" : "/";
// 首先遍歷 $folder 中的所有檔案
$handle = opendir($folder);
while (
$f = readdir($handle)) {
if (
$f != "." && $f != "..") {
if (
is_file($folder . $f)) {
// 如果找到檔案,則將其儲存
// 如果有子資料夾,則儲存到該子資料夾中
if ($subfolder != null)
$zipFile->addFile($folder . $f, $subfolder . $f);
else
$zipFile->addFile($folder . $f);
} elseif (
is_dir($folder . $f)) {
// 如果找到資料夾,則在 zip 檔案中建立一個資料夾
$zipFile->addEmptyDir($f);
// 並再次呼叫此函式
folderToZip($folder . $f, $zipFile, $f);
}
}
}
}
?>

使用方法如下
<?php
$z
= new ZipArchive();
$z->open("test.zip", ZIPARCHIVE::CREATE);
folderToZip("storeThisFolder", $z);
$z->close();
?>

祝你有美好的一天!
panique at web dot de
12 年前
重要事項:由於 zip 檔案的自然檔案大小限制為 4GB(正確來說約為 3.6GB),如果結果大於 4 GB,這個類別將會產生損壞的檔案。使用 tar.gz 是一個合適的替代方案。
ohcc at 163 dot com
9 年前
<?php
//使用 bzip2 + ZipArchive 來減少 zip 壓縮檔的大小。
$zip = new ZipArchive;
$zip->open('i.zip',ZIPARCHIVE::CREATE|ZIPARCHIVE::OVERWRITE);
$file='wuxiancheng.cn.sql';
$bzFilename = $file.'.bz2';
$sql = file_get_contents($file);
$sql = bzcompress($sql,9);
$zip->addFromString($bzFilename,$sql);
$zip->setArchiveComment('zipped on '.date('Y-M-d'));
?>
piotr dot stop dot spam at gmail dot com
10 年前
您可以檢查通用標誌以測試 zip 檔案是否已加密。範例函式如下。

<?php

/**
* 檢查檔案是否已加密
*
* 注意:如果檔案不存在或無法開啟,函式
* 也會回傳 false。
*
* @param string $pathToArchive
* @return boolean 如果檔案已加密則回傳 true
*/
function isEncryptedZip( $pathToArchive ) {
$fp = @fopen( $pathToArchive, 'r' );
$encrypted = false;
if (
$fp && fseek( $fp, 6 ) == 0 ) {
$string = fread( $fp, 2 );
if (
false !== $string ) {
$data = unpack("vgeneral", $string);
$encrypted = $data[ 'general' ] & 0x01 ? true : false;
}
fclose( $fp );
}
return
$encrypted;
}
h-fate at gmx dot net
14 年前
請注意,產生 zip 檔案的演算法有好幾種。例如,我發現使用 ZipArchive 建立的 Office OpenXML 檔案無法被 Excel 2007 辨識。

在這種情況下,您必須使用不同的類別來壓縮,例如 PclZip。
To Top