如何下载压缩文件的子级之一


How to download one of the children of a zipped file

我在PHP中创建了一个Zipped文件,如下所示:

$nameFile = $_FILES['file']['name'];
$tmpName  = $_FILES['file']['tmp_name'];
$fp      = fopen($tmpName, 'r');
$containFile = fread($fp, filesize($tmpName));
fclose($fp);
$zip = new ZipArchive();
$fileconpress = "uploads/".$nameFile.".zip";
$conpress = $zip->open($fileconpress, ZIPARCHIVE::CREATE);
if ($conpress)
{
$zip->addFromString($nameFile, $containFile);
$zip->close();

一切都很完美。在另一个页面中,我列出了我文件夹中的所有压缩文件以及这些压缩文件中的所有子文件(通过我的数据库获得列表)。

我希望能够下载压缩文件中的1个孩子。如何打开服务器上的压缩文件并让用户下载其中一个?

我在php.net上查看了zip_read和zip_open,但它们没有给出太多例子,我很难理解它是如何真正工作的。

php文档中有很多示例:http://php.net/manual/en/function.zip-open.php

只需打开文件,将其解压缩到一个目录,然后为您想要的目录提供服务器。这个设置让我怀疑你是否应该在服务器上准备好解压缩的文件,但这是你的选择。

$zip = new ZipArchive;
$res = $zip->open("uploads/".$parent.".zip");
if ($res === TRUE) {
    $zip->extractTo("uploads/".$parent);
    $zip->close();
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$child.'');
    header('Pragma: no-cache');
    readfile("uploads/".$parent."/".$child);
} else {
    echo 'failed, code:' . $res;
}