[ACCEPTED]-Manipulate an Archive in memory with PHP (without creating a temporary file on disk)-disk

Accepted answer
Score: 50

I had the same problem but finally found 16 a somewhat obscure solution and decided 15 to share it here.

I came accross the great 14 zip.lib.php/unzip.lib.php scripts which come with phpmyadmin and are located 13 in the "libraries" directory.

Using 12 zip.lib.php worked as a charm for me:

require_once(LIBS_DIR . 'zip.lib.php');


//create the zip
$zip = new zipfile();

//add files to the zip, passing file contents, not actual files
$zip->addFile($file_content, $file_name);


//prepare the proper content type
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=my_archive.zip");
header("Content-Description: Files of an applicant");

//get the zip content and send it back to the browser
echo $zip->file();

This script allows 11 downloading of a zip, without the need of 10 having the files as real files or saving 9 the zip itself as a file.

It is a shame that 8 this functionality is not part of a more 7 generic PHP library.

Here is a link to the 6 zip.lib.php file from the phpmyadmin source: https://github.com/phpmyadmin/phpmyadmin/blob/RELEASE_4_5_5_1/libraries/zip.lib.php

UPDATE: Make 5 sure you remove the following check from 4 the beginning of zip.lib.php as otherwise 3 the script just terminates:

if (! defined('PHPMYADMIN')) {

UPDATE: This code is 2 available on the CodeIgniter project as 1 well: https://github.com/patricksavalle/CodeIgniter/blob/439ac3a87a448ae6c2cbae0890c9f672efcae32d/system/helpers/zip_helper.php

Score: 3

what are you using to generate the archive? You 3 might be able to use the stream php://temp 2 or php://memory to read and write to/from 1 the archive.

See http://php.net/manual/en/wrappers.php.php

Score: 2

Regarding your comment that php://temp works 5 for you except when you close it, try keeping 4 it open, flushing the output, then rewind 3 it back to 0 and read it.

Look here for 2 more examples: http://us.php.net/manual/en/function.tmpfile.php

Also research output buffering 1 and capturing: http://us.php.net/manual/en/function.ob-start.php

Score: 0

You need to use ZipArchive::addFromString - if you use addFile() the file 5 is not actually added until you go to close 4 it. (Horrible bug IMHO, what if you are 3 trying to move files into a zip and you 2 delete them before you close the zip...)
The 1 addFromString() method adds it to the archive immediately.

More Related questions