PHP 压缩文件需要用到 ZipArchive 类,Windows 环境需要打开 php_zip.dll扩展。
压缩文件
$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(); }
下载压缩包
下载压缩包需要先将目标目录压缩,然后下载压缩包,最后删除压缩包。
在压缩目录示例中,追加以下代码:
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\');