ZipArchive 是 PHP 內建的 Zip模組,可以將你的目錄及檔案進行壓縮與解壓縮
免去一個一個檔案去備份下載或上傳
ZipArchive函數 支援範圍
PHP 5 >= 5.2.0, PHP 7
將所在的目錄內,所有資料夾與檔案 壓縮
<?php class ToZip{ 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); }else if(is_dir($filePath)){ // Add sub-directory. $zipFile->addEmptyDir($localPath); self::folderToZip($filePath, $zipFile, $exclusiveLength); } } } closedir($handle); } 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(); echo "BackupiZO.zip 壓縮完成"; } } ToZip::zipDir(dirname(__FILE__), dirname(__FILE__).'/BackupiZO.zip'); ?>
將 zip壓縮檔 進行 解壓縮
<?php $zip=new ZipArchive; if($zip->open('BackUp-iZO.zip')===TRUE){ $zip->extractTo('backup'); //避免覆蓋,將解壓縮資料放進該資料夾 $zip->close(); echo "解壓縮完成"; } ?>
將特定檔案進行 壓縮
<?php $zip=new ZipArchive; if($zip->open('BackupiZO.zip',ZipArchive::OVERWRITE)===TRUE){ $zip->addFile('image.txt');//欲壓縮檔案 $zip->close(); echo "壓縮完成"; } ?>
常見問題
Fatal error: Class ‘ZipArchive’ not found
如果在 php 7 出現該錯誤訊息
只要重新運行
sudo apt-get install php7.0-zip
sudo service apache2 restart
就可以正常運作囉!