使用PHP类ZipArchive创建一个zip文件而不将文件写入磁盘?

时间:2010-11-12 13:51:20

标签: php ziparchive

我想使用ZipArchive(或本机PHP类)在内存中创建一个zip文件,并将文件内容读回客户端。这可能吗?如果是这样,怎么样?

我想在此应用程序中压缩的文件总共最多15 MB。我认为我们应该记忆良好。

4 个答案:

答案 0 :(得分:4)

查看以下库,它允许创建zip文件并将其作为流返回:PHPClasses.org

答案 1 :(得分:3)

感谢Frosty Z提供的出色库ZipStream-PHP。我们有一个用例,可以将数量和大小上大的zip文件上传到S3。官方文档没有提及如何上传到S3。

因此我们有一个想法,可以将ZipStream输出创建的zip直接流式传输到S3,而无需在服务器上创建zip文件。

以下是我们提供的有效示例代码:

<?php
# Autoload the dependencies
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use ZipStream\Option\Archive as ArchiveOptions;

//s3client service
$s3Client = new S3Client([
    'region' => 'ap-southeast-2',
    'version' => 'latest',
    'credentials' => [
        'key' => '<AWS_KEY>',
        'secret' => '<AWS_SECRET_KEY>',
    ]
]);
$s3Client->registerStreamWrapper(); //required

$opt = new ArchiveOptions();
$opt->setContentType('application/octet-stream');
$opt->setEnableZip64(false); //optional - for MacOs to open archives

$bucket = 'your_bucket_path';
$zipName = 'target.zip';

$zip = new ZipStream\ZipStream($zipName, $opt);

$path = "s3://{$bucket}/{$zipName}";
$s3Stream = fopen($path, 'w');

$zip->opt->setOutputStream($s3Stream); // set ZipStream's output stream to the open S3 stream

$filePath1 = './local_files/document1.zip';
$filePath2 = './local_files/document2.zip';
$filePath3 = './local_files/document3.zip';

$zip->addFileFromPath(basename($filePath1), $filePath1);
$zip->addFileFromPath(basename($filePath2), $filePath2);
$zip->addFileFromPath(basename($filePath3), $filePath3);

$zip->finish(); // sends the stream to S3
?>

答案 2 :(得分:1)

尝试ZipStream(链接到GitHub repo,也支持通过Composer安装)。

来自原作者的网站(现已死亡):

  

ZipStream是一个动态流动态zip文件的库   来自PHP而无需在服务器上写入磁盘。

答案 3 :(得分:0)

还有另一个话题在谈论这个问题: Manipulate an Archive in memory with PHP (without creating a temporary file on disk)

nettle建议使用phpmyadmin中的zip.lib.php。我认为这是一个相当可靠的解决方案。

仅供参考 zip.lib.php ,它已被相同的库/文件夹中的 ZipFile.php 取代。