PHP Zip 3 small text files and force download

2019-01-20 12:37发布

问题:

My website writes 3 small text files based on users information and then presents these 3 files as links that they must "right click" and save to their desktop.

I would like to keep that, but also somehow offer a way to zip these 3 small files up and force download. And I don't want to save the zip file on the server either. Can this be done and how?

Thanks!

回答1:

For the forced download you need to send out the file headers first.

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

For zipping you'll wanna use one PHP's zip libraries, then echo/output the zipped content.

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

Something like this:

$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.


标签: php zip stream