一、準備工作,使用phpinfo()查看有沒有zip擴展
<?php
echo phpinfo();
?>
Thinkphp使用PHP自帶的ZipArchive壓縮文件或文件夾
顯示enabled 說明已經配置好
如果沒有安裝擴展的,請參照以下方法:
1、下載對應版本的擴展包:https://windows.php.net/downloads/pecl/releases/zip/1.20.0/,比如我是php7.4(window7_64位系統),則下載如下:
Thinkphp使用PHP自帶的ZipArchive壓縮文件或文件夾
2、把解壓的php_zip.dll文件放到php-5.6.27-nts/ext目錄
3、在php.ini添加以下配置:
extension=php_zip.dll
4、重啟Apache
二、在控制器中使用
//文件夾打包
public function zip()
{$local = app()->getRootPath().'\public';try {//文件夾目錄$dirPath = $local."\demo";//zip壓縮包保存路徑$zipPath = $local."\demo.zip";//創建zip實例$zip=new \ZipArchive();if($zip->open($zipPath, \ZipArchive::CREATE|\ZipArchive::OVERWRITE)=== TRUE) {//調用方法,對要打包的根目錄進行操作,并將ZipArchive的對象傳遞給方法$this->addFileToZip($zip,$dirPath,$dirPath);//關閉處理的zip文件$zip->close();}}catch (\Exception $e) {//echo '壓縮失敗';halt($e);}//echo '壓縮成功';$this->downloadZip($zipPath);
}//下載function
public function downloadZip($zipPath)
{$zipPath = iconv("UTF-8", "GBK", $zipPath);//加這行中文文件夾也ok了header("Cache-Control: public");header("Content-Description: File Transfer");header('Content-disposition: attachment; filename=' . basename($zipPath)); //文件名header("Content-Type: application/zip"); //zip格式的header("Content-Transfer-Encoding: binary"); //告訴瀏覽器,這是二進制文件header('Content-Length: ' . filesize($zipPath)); //告訴瀏覽器,文件大小@readfile($zipPath);//ob_end_clean();@unlink(app()->getRootPath().'public/'.$zipPath);//刪除壓縮包
}//壓縮包追加文件
public function addFileToZip($zip,$path,$root){$handler=opendir($path); //打開當前文件夾while(($filename=readdir($handler))!==false){if($filename != "." && $filename != ".."){//不操作名字為'.'和'..'的文件夾或文件if(is_dir($path."/".$filename)){// 如果讀取的某個對象是文件夾,則遞歸$this->addFileToZip($zip,$path."/".$filename,$root);}else{//將文件加入zip對象,第二個參數是zip里文件的路徑$pathFilename=$path . "/" . $filename;$zip->addFile($pathFilename, str_replace($root.'/','',$pathFilename));}}}//@closedir($path);
}
小伙伴們,以上親測有效,記得關注