PHP 中的 Zip 流
我有一个 PHP 脚本,可以动态创建 zip 文件并强制浏览器下载该 zip 文件。问题是:我可以直接将zip文件写入连接到用户浏览器的输出流,而不是先将其保存为服务器上的真实文件,然后发送文件吗?
提前致谢。
I have a PHP script that creates a zip file on the fly and forces the browser to download the zip file. The question is: could I directly write the zip file to an output stream which is connected to the user's browser rather than save it as a real file on the server first and then send the file?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您的网络服务器运行的是 Linux,那么您可以在不生成临时文件的情况下进行流式传输。在Win32下,您可能需要使用Cygwin或类似的东西。
如果您使用
-
作为 zip 文件名,它将压缩到 STDOUT。可以使用passthru()
将其直接重定向到请求者。-q
参数只是告诉zip
不要输出通常会输出的状态文本。有关详细信息,请参阅 zip(1) 联机帮助页。If your web server is running Linux, then you can do it streaming without a temp file being generated. Under Win32, you may need to use Cygwin or something similar.
If you use
-
as the zip file name, it will compress to STDOUT. That can be redirected straight to the requester usingpassthru()
. The-q
argument simply tellszip
to not output the status text it normally would. See the zip(1) manpage for more info.这个库似乎就是您正在寻找的:
https://github.com/maennchen/ZipStream-PHP
This library seems to be what you're looking for:
https://github.com/maennchen/ZipStream-PHP
如果您使用 zip 扩展,答案似乎是“不。” ZipArchive 类中的 close 方法 触发写入,它似乎想写入一个文件。使用Streams可能有一些运气模拟一个文件,但是你将整个文件保存在内存中,并且在添加完文件之前你仍然无法发送它。
如果您在让用户等待创建 zip 文件时遇到超时或其他问题,请尝试多步骤下载过程:
If you're using the zip extension, the answer seems to be "no." The close method in the ZipArchive class is what triggers a write, and it seems to want to write to a file. You might have some luck using Streams to simulate a file, but then you're keeping the entire thing in memory, and you still couldn't send it until you're done adding files.
If you're having problems with timeouts or other problems while having a user wait for the zip file to be created, try a multi-step download process:
是的,您可以使用以下 git 代表直接将 zip 流式传输到客户端: 压缩流大文件
Yes, you can directly stream the zip to the client using this git rep: Zip Stream Large Files
不,您必须使用临时文件,如此处< /a>.
No, you have to use a temporary file, as in here.