php实现zip压缩
使用 ZipArchive 类实现压缩
ZipArchive 是 PHP 内置的扩展类,用于创建和操作 ZIP 压缩文件。确保 PHP 已启用该扩展(php.ini 中 extension=zip)。

$zip = new ZipArchive();
$zipName = 'archive.zip';
if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
// 添加文件到压缩包
$zip->addFile('path/to/file1.txt', 'file1.txt'); // 第二个参数可指定压缩包内路径
$zip->addFile('path/to/file2.jpg', 'images/file2.jpg');
// 添加目录(递归)
$dir = 'path/to/folder';
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($files as $file) {
if (!$file->isDir()) {
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($dir) + 1);
$zip->addFile($filePath, 'folder/' . $relativePath);
}
}
// 添加纯文本内容(无需实际文件)
$zip->addFromString('readme.txt', 'This is a generated ZIP file.');
$zip->close();
echo "ZIP created successfully.";
} else {
echo "Failed to create ZIP.";
}
使用命令行调用 zip 工具
若服务器已安装 zip 命令(Linux/Unix 环境),可通过 exec() 或 shell_exec() 调用系统命令实现压缩:

$filesToZip = 'file1.txt file2.jpg';
$zipName = 'archive.zip';
$command = "zip -r $zipName $filesToZip";
exec($command, $output, $returnCode);
if ($returnCode === 0) {
echo "ZIP created via command line.";
} else {
echo "Command failed: " . implode("\n", $output);
}
动态生成 ZIP 并强制下载
以下代码直接输出 ZIP 到浏览器,触发下载:
$zip = new ZipArchive();
$zipName = 'dynamic_archive.zip';
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipName . '"');
// 使用输出缓冲区捕获 ZIP 内容
$tempFile = tempnam(sys_get_temp_dir(), 'zip');
if ($zip->open($tempFile, ZipArchive::CREATE) === TRUE) {
$zip->addFile('path/to/file.pdf', 'document.pdf');
$zip->addFromString('note.txt', 'Downloaded on: ' . date('Y-m-d'));
$zip->close();
readfile($tempFile);
unlink($tempFile); // 清理临时文件
exit;
} else {
header('HTTP/1.1 500 Server Error');
echo "ZIP generation failed.";
}
注意事项
- 文件路径需确保 PHP 有读取权限,输出目录需有写入权限。
- 大文件压缩时建议增加
set_time_limit(0)避免超时。 - 动态下载时需确保无任何输出(包括空格)在
header()前。 - 使用
RecursiveDirectoryIterator时注意排除.和..目录。






