PHP下载压缩包文件

压缩文件

 1 $zip = new ZipArchive(); 2 // 打开一个zip文档,ZipArchive::OVERWRITE:如果存在这样的文档,则覆盖;ZipArchive::CREATE:如果不存在,则创建 3 $res = $zip->open(‘test.zip‘, ZipArchive::OVERWRITE | ZipArchive::CREATE); 4 if($res) 5 { 6 // 添加 a.txt 到压缩文档 7 $zip->addFile(‘a.txt‘); 8 // 添加一个字符串到压缩文档中的b.txt 9 $zip->addFromString(‘b.txt‘, ‘this is b.txt‘);10 // 添加一个空目录b到压缩文档11 $zip->addEmptyDir(‘b‘);12 }13 // 关闭打开的压缩文档14 $zip->close();

压缩目录

 1 1 /** 2  2 * @param $dir 目标目录路径 3  3 * @param $zip ZipArchive类对象 4  4 * @param $prev 5  5 */ 6 6 function compressDir($dir, $zip, $prev=‘.‘) 7 7 { 8 8 $handler = opendir($dir); 9 9 $basename = basename($dir);10 10 $zip->addEmptyDir($prev . ‘/‘ . $basename);11 11 while($file = readdir($handler))12 12 {13 13 $realpath = $dir . ‘/‘ . $file;14 14 if(is_dir($realpath))15 15 {16 16 if($file !== ‘.‘ && $file !== ‘..‘)17 17 {18 18 $zip->addEmptyDir($prev . ‘/‘ . $basename . ‘/‘ . $file);19 19 compressDir($realpath, $zip, $prev . ‘/‘ . $basename);20 20 }21 21 }else22 22 {23 23 $zip->addFile($realpath, $prev. ‘/‘ . $basename . ‘/‘ . $file);24 24 }25 25 }26 26 27 27 closedir($handler);28 28 return null;29 29 }30 30 31 31 $zip = new ZipArchive();32 32 $res = $zip->open(‘test.zip‘, ZipArchive::OVERWRITE | ZipArchive::CREATE);33 33 if($res)34 34 {35 35 compressDir(‘./test‘, $zip);36 36 $zip->close();37 37 }

解压缩

1 $zip = new ZipArchive();2 $res = $zip->open(‘test1.zip‘);3 if($res)4 {5 // 解压缩文件到指定目录6 $zip->extractTo(‘test‘);7 $zip->close();8 }

下载压缩包

1 header(‘Content-Type:text/html;charset=utf-8‘);2 header(‘Content-disposition:attachment;filename=test.zip‘);3 $filesize = filesize(‘./test.zip‘);4 readfile(‘./test.zip‘);5 header(‘Content-length:‘.$filesize);6 7 unlink(‘./test.zip‘);

 

相关文章