使用php创建和提供压缩文件 [英] Creating and serving zipped files with php

查看:97
本文介绍了使用php创建和提供压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码从目录创建一个zip文件,并通过http下载将其提供给用户:

 // write the file
file_put_contents($path . "/index.html", $output);

// zip up the contents
chdir($path);
exec("zip -r {$course->name} ./");

$filename = "{$course->name}.zip";

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' .urlencode($filename));
header('Content-Transfer-Encoding: binary');

readfile($filename);

我能够创建zip文件,但是无法通过http下载.如果我下载使用ftp客户端创建的zip文件,则Mac的Stuffit Expander可以很好地解压缩文件,但是如果我通过http下载,则mac解压缩器会产生无限循环.我的意思是说我下载的文件称为course.zip,然后解压缩该文件将得到course.zip.cpgz,然后再次解压缩该文件将得到course.zip.

有人有什么主意吗?

谢谢!

解决方案

  1. 每次都将其重新压缩不是一个好主意.仅当ZIP文件尚不存在时,才尝试这样做.

  2. 如果是易失性文件,或者只是一个要传输的压缩小文件,请尝试使用ob_start('ob_gzhandler'),而不是更简单,更小,更干净.该文件已压缩传输,但在客户端以原始格式保存.

  3. 需要指定Content-Length标头,以允许下载程序知道文件的结尾,允许进度控制,检测文件损坏并避免HTTP会话挂起(如果Connection在Keep中-live模式),也许缺少此标头是问题的根源.

I'm trying to use the following code to create a zip file from a directory and serve it to the user via an http download:

 // write the file
file_put_contents($path . "/index.html", $output);

// zip up the contents
chdir($path);
exec("zip -r {$course->name} ./");

$filename = "{$course->name}.zip";

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' .urlencode($filename));
header('Content-Transfer-Encoding: binary');

readfile($filename);

I am able to create the zip file, but downloading it over http is not working. If I download the zip file that's created using an ftp client then Mac's Stuffit Expander unzips the files just fine, but if I download it over http, the mac unzipper creates an endless loop. What I mean by this is say the file I download is called course.zip, then unzipping the file gives course.zip.cpgz and unzipping that file gives course.zip again..and on and on.

Anyone have any ideas?

Thanks!

解决方案

  1. Re-zipping it every time it is requested is not a good idea. Try doing that only if the ZIP file does not exist already.

  2. If is a volatile file or just a single small file you want to transfer compressed, try using ob_start('ob_gzhandler') instead, simplier, smaller, cleaner. The file is transfered compressed, but it is saved in its original format by the client-side.

  3. Specifying the Content-Length header is needed to allow the downloader to know the end of the file, allowing progress control, detection of corruption of the file and avoiding the hang of the HTTP session (if Connection is in Keep-Alive mode), maybe the lack of this header is the root of the problem.

这篇关于使用php创建和提供压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆