PHP ZIP files on the fly

What's the easiest way to zip, say 2 files, from a folder on the server and force download? Without saving the "zip" to the server.

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

Can someone verify: I have a folder with test1.doc, test2.doc, and test3.doc

with the above example - file1 (file2 and file3) might just be test1.doc, etc.

do I have to do anything with "$filepath1"? Is that the folder directory that holds the 3 docs?

Sorry for my basic question..


Solution 1:

Unfortunately w/ PHP 5.3.4-dev and Zend Engine v2.3.0 on CentOS 5.x I couldn't get the code above to work. An "Invalid or unitialized Zip object" error message was all I could get. So, in order to make it work, I had to use following snippet (taken from the example by Jonathan Baltazar on PHP.net manual, at the ZipArchive::open page):

// Prepare File
$file = tempnam("tmp", "zip");
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);

// Stuff with content
$zip->addFromString('file_name_within_archive.ext', $your_string_data);
$zip->addFile('file_on_server.ext', 'second_file_name_within_archive.ext');

// Close and send to users
$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file); 

I know this is different than working w/ memory only - unless you have your tmp area in ram ;-) - but maybe this can help out someone else, who's struggling with the solution above, like I was; and for which performance penalty is not an issue.

Solution 2:

Your code is very close. You need to use the file name instead of the file contents.

$zip->addFile(file_get_contents($filepath1), 'file1');

should be

$zip->addFile($filepath1, 'file1');

http://us3.php.net/manual/en/function.ziparchive-addfile.php

If you need to add files from a variable instead of a file you can use the addFromString function.

$zip->addFromString( 'file1', $data );