如何压缩文件夹并使用php下载它? [英] How to zip a folder and download it using php?
问题描述
我有一个名为"data"的文件夹.该数据"文件夹包含一个文件"filecontent.txt"和另一个名为文件"的文件夹. 文件"文件夹包含一个"info.txt"文件. 所以它是文件夹结构内的一个文件夹.
I have folder named "data". This "data" folder contains a file "filecontent.txt" and another folder named "Files". The "Files" folder contains a "info.txt" file. So it is a folder inside folder structure.
我必须将此文件夹数据"(使用php)连同其中的文件和文件夹一起压缩,然后下载压缩文件.
I have to zip this folder "data"(using php) along with the file and folder inside it, and download the zipped file.
我尝试了 http://www.php.net上可用的示例/manual/zh-CN/zip.examples.php 这些示例不起作用.我的PHP版本是5.2.10
I have tried the examples available at http://www.php.net/manual/en/zip.examples.php These examples did not work. My PHP version is 5.2.10
请帮助.
我已经编写了这段代码.
I have written this code.
<?php
$zip = new ZipArchive;
if ($zip->open('check/test2.zip',ZIPARCHIVE::CREATE) === TRUE) {
if($zip->addEmptyDir('newDirectory')) {
echo 'Created a new directory';
} else {
echo 'Could not create directory';
}
$zipfilename="test2.zip";
$zipname="check/test2.zip";
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=check/test1.zip'); //header('Content-Length: ' . filesize( $zipfilename));
readfile($zipname); //$zip->close(); } else { echo failed';
}
?>
文件已下载但无法解压缩
file downloaded but could not unzip
推荐答案
您需要以递归方式在目录中添加文件.像这样(未经测试):
You need to recursively add files in the directory. Something like this (untested):
function createZipFromDir($dir, $zip_file) {
$zip = new ZipArchive;
if (true !== $zip->open($zip_file, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
return false;
}
zipDir($dir, $zip);
return $zip;
}
function zipDir($dir, $zip, $relative_path = DIRECTORY_SEPARATOR) {
$dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (file === '.' || $file === '..') {
continue;
}
if (is_file($dir . $file)) {
$zip->addFile($dir . $file, $file);
} elseif (is_dir($dir . $file)) {
zipDir($dir . $file, $zip, $relative_path . $file);
}
}
}
closedir($handle);
}
然后致电$zip = createZipFromDir('/tmp/dir', 'files.zip');
为了获得更大的胜利,我建议您阅读SPL DirectoryIterator
此处
For even more win I'd recommend reading up on the SPL DirectoryIterator
here
这篇关于如何压缩文件夹并使用php下载它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!