### 批量压缩文件并下载zip示例
function deleteDir($dirName)
{
if(file_exists($dirName)){//判断目录是否存在
//如果是目录,那么我们就遍历下面的文件或者目录
//打开目录句柄
$dir = opendir($dirName);
while($fileName = readdir($dir)){
//不运行像上级目录运行
if($fileName!="." && $fileName!=".."){
$file = $dirName."/".$fileName;
echo "||".$file."||";
if(is_dir($file)){
deleteDir($file);//使用递归删除目录
}else{
echo "--delete-".$file."++";
unlink($file);
}
}
}
closedir($dir);//关闭dir
if( rmdir( $dirName ) )echo "成功删除目录: $dirName";
}else{
echo "对不起,目录不存在";
}
}
$source = __DIR__.'/test';
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source));
$zip = new ZipArchive();
$zipfile = $source . '.zip';
if (!$zip->open($zipfile, ZipArchive::CREATE)) {
echo '压缩包创建失败';
exit;
}
foreach($files as $file){
$file = str_replace('\\', '/', $file);
//忽略当前目录和上级目录
if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) {
continue;
}
if (is_dir($file) === true) {
//创建一个子目录
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if (is_file($file) === true) {
//创建一个子文件
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
} else if (is_file($source) === true) {
//创建文件根目录下的文件
$zip->addFromString(basename($source), file_get_contents($source));
}
}
$zip->close();
//返回文件类型
$ua = $_SERVER["HTTP_USER_AGENT"];
Header('Content-type: application/zip');
//返回文件的字节大小
Header('Accept-Range: bytes');
Header("Content-Transfer-Encoding: Binary");
//返回文件大小
Header('Accept-Length: ' . filesize($zipfile));
header('Cache-Control: max-age=0');
//这里对客户端弹出的对话框,对应的文件名
$basename = preg_replace('/^.+[\\\\\\/]/', '', $zipfile);
$encode_filename = urlencode($basename);
if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename="' . $basename . '"');
} else if (preg_match("/Chrome/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encode_filename. '"');
} else {
$encoded_filename = str_replace("+", "%20", $encode_filename);
header('Content-Disposition: attachment; filename="' . $encode_filename. '"');
}
@readfile($zipfile);
//删除文件
unlink($zipfile);
deleteDir($source);
exit;