PHP Zip 3小文本文件并强行下载

时间:2009-06-05 02:14:54

标签: php zip stream

我的网站根据用户信息编写3个小文本文件,然后将这3个文件显示为必须“右键单击”并保存到桌面的链接。

我想保留它,但也以某种方式提供了一种方法来压缩这3个小文件并强行下载。我也不想将zip文件保存在服务器上。可以这样做吗?

谢谢!

1 个答案:

答案 0 :(得分:12)

对于强制下载,您需要先发送文件头。

header('content-type: application/zip');
header('content-disposition: inline; filename=YOUR_ZIP_FILE_NAME_HERE.ZIP"');

对于压缩,您需要使用一个PHP的zip库,然后回显/输出压缩内容。

http://ca3.php.net/manual/en/zip.examples.php

这样的事情:

$zip = new ZipArchive();
//the string "file1" is the name we're assigning the file in the archive
$zip->addFile(file_get_contents($filepath1), 'file1'); //file 1 that you want compressed
$zip->addFile(file_get_contents($filepath2), 'file2'); //file 2 that you want compressed
$zip->addFile(file_get_contents($filepath3), 'file3'); //file 3 that you want compressed
echo $zip->file(); //this sends the compressed archive to the output buffer instead of writing it to a file.