PHP 壓縮文件須要用到 ZipArchive
類,Windows 環境須要打開 php_zip.dll
擴展。php
$zip = new ZipArchive(); // 打開一個zip文檔,ZipArchive::OVERWRITE:若是存在這樣的文檔,則覆蓋;ZipArchive::CREATE:若是不存在,則建立 $res = $zip->open('test.zip', ZipArchive::OVERWRITE | ZipArchive::CREATE); if($res) { // 添加 a.txt 到壓縮文檔 $zip->addFile('a.txt'); // 添加一個字符串到壓縮文檔中的b.txt $zip->addFromString('b.txt', 'this is b.txt'); // 添加一個空目錄b到壓縮文檔 $zip->addEmptyDir('b'); } // 關閉打開的壓縮文檔 $zip->close();
1 /** 2 * @param $dir 目標目錄路徑 3 * @param $zip ZipArchive類對象 4 * @param $prev 5 */ 6 function compressDir($dir, $zip, $prev='.') 7 { 8 $handler = opendir($dir); 9 $basename = basename($dir); 10 $zip->addEmptyDir($prev . '/' . $basename); 11 while($file = readdir($handler)) 12 { 13 $realpath = $dir . '/' . $file; 14 if(is_dir($realpath)) 15 { 16 if($file !== '.' && $file !== '..') 17 { 18 $zip->addEmptyDir($prev . '/' . $basename . '/' . $file); 19 compressDir($realpath, $zip, $prev . '/' . $basename); 20 } 21 }else 22 { 23 $zip->addFile($realpath, $prev. '/' . $basename . '/' . $file); 24 } 25 } 26 27 closedir($handler); 28 return null; 29 } 30 31 $zip = new ZipArchive(); 32 $res = $zip->open('test.zip', ZipArchive::OVERWRITE | ZipArchive::CREATE); 33 if($res) 34 { 35 compressDir('./test', $zip); 36 $zip->close(); 37 }
$zip = new ZipArchive(); $res = $zip->open('test1.zip'); if($res) { // 解壓縮文件到指定目錄 $zip->extractTo('test'); $zip->close(); }
下載壓縮包須要先將目標目錄壓縮,而後下載壓縮包,最後刪除壓縮包。html
在壓縮目錄示例中,追加如下代碼:this
header('Content-Type:text/html;charset=utf-8'); header('Content-disposition:attachment;filename=test.zip'); $filesize = filesize('./test.zip'); readfile('./test.zip'); header('Content-length:'.$filesize); unlink('./test.zip');