如何使用php的ziparchive类实现文件和目录的压缩?1. 创建压缩包:使用ziparchive类并调用addfile方法添加文件,通过ziparchive::create参数创建新文件;2. 压缩整个目录:递归遍历目录并逐个添加文件,注意路径拼接及过滤规则;3. 设置密码与注释:通过系统命令实现加密,使用setarchivecomment方法添加注释;4. 动态生成zip并输出:利用临时文件保存zip内容,设置header后输出给浏览器并清理缓存。

PHP压缩文件其实挺常见,尤其是在做文件打包下载、备份或者上传多文件处理的时候。用得最多的就是ZipArchive这个类了,它功能全、使用也方便。不过很多人只会基本的打包,其实它还有一些高级用法,能让你的操作更灵活。

这是最基础的操作,但也有一些细节需要注意。

$zip = new ZipArchive();
$filename = "example.zip";
if ($zip->open($filename, ZipArchive::CREATE) === TRUE) {
$zip->addFile("file1.txt", "newname.txt"); // 添加文件并指定在zip中的名称
$zip->addFile("file2.txt");
$zip->close();
}ZipArchive::CREATE:如果文件不存在就创建。有时候我们需要把一个完整的目录结构打包,这时候就需要自己写个小函数来递归处理。
立即学习“PHP免费学习笔记(深入)”;
function addDirToZip($dir, $zip, $basePath = '') {
$files = scandir($dir);
foreach ($files as $file) {
if ($file == '.' || $file == '..') continue;
$filePath = $dir . '/' . $file;
$localPath = $basePath . '/' . $file;
if (is_dir($filePath)) {
addDirToZip($filePath, $zip, $localPath);
} else {
$zip->addFile($filePath, ltrim($localPath, '/'));
}
}
}
$zip = new ZipArchive();
$zip->open('backup.zip', ZipArchive::CREATE);
addDirToZip('my_folder', $zip);
$zip->close();.git或cache目录。ZipArchive本身不支持加密(也就是带密码的压缩),但你可以通过执行系统命令调用外部工具,比如zip命令。

exec('zip -P mypassword secure.zip file1.txt file2.txt');-P 参数后面跟的是密码。至于注释,ZipArchive提供了方法:
$zip->setArchiveComment('这是一个带注释的压缩包');有时候我们不想把zip保存到服务器上,而是直接让用户下载。
$zip = new ZipArchive();
$tmpFile = tempnam(sys_get_temp_dir(), 'zip');
if ($zip->open($tmpFile, ZipArchive::CREATE) === TRUE) {
$zip->addFromString('hello.txt', 'This is a test file');
$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($tmpFile));
header('Content-Disposition: attachment; filename="download.zip"');
readfile($tmpFile);
unlink($tmpFile); // 下载完删除临时文件
}tempnam()生成临时文件,避免冲突。这些就是PHP中使用ZipArchive的一些进阶操作。虽然有些功能原生不支持,比如加密码,但结合系统命令也能实现。关键是理解流程,再根据实际需求调整代码。基本上就这些。
以上就是如何使用PHP压缩文件?ZipArchive高级用法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号