PHP zip 函数制作 zip 但下载
我有一个名为 zip
的函数,它可以从文件夹中生成 zip 文件。工作完美,除了制作完成后下载 zip 之外。我希望用户能够按需下载并进行备份。但它们在制作时也会被下载。这是我的 PHP 代码:
function zip($source, $destination){
if (extension_loaded('zip') === true){
if (file_exists($source) === true){
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE) === true ){
$source = realpath($source);
if (is_dir($source) === true){
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file){
$file = realpath($file);
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));
}
}
return $zip->close();
}
}
return false;
}
zip("../data", "backup.zip");
有谁知道如何解决我的问题?提前致谢!
注意:
纯文本版本为:此处
I have a function, called zip
, that makes a zip out of a folder. Works perfectly, except that it downloads the zip after making it. I want users to be able to download and make backups on demand. But they are download when they are made as well. This is my PHP code:
function zip($source, $destination){
if (extension_loaded('zip') === true){
if (file_exists($source) === true){
$zip = new ZipArchive();
if ($zip->open($destination, ZIPARCHIVE::CREATE) === true ){
$source = realpath($source);
if (is_dir($source) === true){
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file){
$file = realpath($file);
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));
}
}
return $zip->close();
}
}
return false;
}
zip("../data", "backup.zip");
Does anyone know how to fix my problem? Thanks in advance!
Note:
The plain-text version is: here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到了类似的问题,但我以不同的方式制作 zip 文件,所以我不知道这是否适用。我的问题是 Internet Explorer,当用户单击链接时,我会创建 zip 文件,在 IE 中,完成后会自动下载,但其他浏览器可以正常工作。
我会检查链接中的 $_SERVER["HTTP_USER_AGENT"] ,并且必须向其中添加“target=_blank”以阻止 IE 自动下载。
I had a similar problem but I was making the zip files differently so I dont know if this will apply. My issue was with Internet Explorer, I would create the zip file when the user clicked a link and in IE it would auto download when it was done but the other browsers would work fine.
I would check for the $_SERVER["HTTP_USER_AGENT"] in my link and I had to add "target=_blank" to it in order to stop IE from auto downloading.