0

I want to construct a zip and serve it back to the user. I currently use Symfony and so far I have the following which works well:

// Create zip.
$zip = new \ZipArchive();
$zip->open('/tmp/foo.zip', \ZipArchive::CREATE);
$zip->addFromString("test1.txt", "test 1 content");
$zip->addFromString("test2.txt", "test 2 content");
$zip->close();

// Read zip.
$stream = fopen('/tmp/foo.zip', 'r');
$zipData = fread($stream, 1024);
fclose($stream);
unlink('/tmp/foo.zip');

// Serve zip.
$response = new Response($zipData);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment; filename=foo.zip');
return $response;

My problem is that I want to avoid having to use the file system (/tmp/foo.zip). I tried $zip->open('php://memory', ...) which I thought that would do the job but it didn't work (result file was always 0 bytes). Is there a way to solve this?

Edit: I want to be using vanilla PHP and not directly make use of commands of the underlying O/S.

cherouvim
  • 31,725
  • 15
  • 104
  • 153
  • 1
    Not possible with PHP streams as the ZipArchive forcibly needs a file name to create the archive. Below thread seems to do what you wish for. – nice_dev Dec 08 '22 at 09:33
  • Does this answer your question? [LAMP: How to create .Zip of large files for the user on the fly, without disk/CPU thrashing](https://stackoverflow.com/questions/4357073/lamp-how-to-create-zip-of-large-files-for-the-user-on-the-fly-without-disk-cp) – nice_dev Dec 08 '22 at 09:33
  • @nice_dev thanks but I want to be using vanilla PHP and not commands of the underlying O/S. – cherouvim Dec 08 '22 at 10:36
  • Well, I am afraid, it ain't possible then. – nice_dev Dec 08 '22 at 10:57
  • 1
    I don't think the feature is supported natively. There's a [third-party package](https://github.com/maennchen/ZipStream-PHP). – Álvaro González Dec 08 '22 at 11:03

0 Answers0