how - php ziparchive not working




PHP ZIP files on the fly (4)

If you have access to the zip commandline utility you can try

<?php
$zipped_data = `zip -q - files`;
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="download.zip"');
echo $zipped_data;
?>

where files is the things you want to zip and zip the location to the zip executable.

This assumes Linux or similar, of course. In Windows you might be able to do similar with another compression tool, I guess.

There's also a zip extension, usage shown here.

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


To create ZIP files on the fly (in memory), you can use ZipFile class from phpMyAdmin:

An example of how to use it in your own application:

  • https://.com/a/9648562/767871

Note: Your ZIP files will be limited by PHP's memory limit, resulting in corrupted archive if you exceed the limit.


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 );

itsols If you want to insert the 'Content-Length' do it like this:

$length = filesize($file);
header('Content-Length: ' . $length);

I don't know why, but it crashes if you put it in the same line.





zip