Create In-memory ZIP Archive in PHP 8.6

Create In-memory ZIP Archive in PHP 8.6

In PHP, the ZipArchive class creates and reads ZIP archives. The archive always had to be a file on disk, because ZipArchive::open takes a path. Building an archive to send over the network therefore meant writing a temporary file first and deleting it afterwards.

Since PHP 8.6, the ZipArchive::openString and ZipArchive::closeString methods make it possible to keep the whole archive in memory. Calling openString without an argument starts an empty archive, and closeString returns the finished archive as a string:

<?php

$zip = new ZipArchive();
$zip->openString();

$zip->addFromString('hello.txt', 'Hello');
$zip->addFromString('data.json', '{"name":"John"}');

$data = $zip->closeString();

echo strlen($data); // 230
file_put_contents('archive.zip', $data);

The string contains a complete archive, so it can be sent straight to the browser as a download or uploaded to object storage. The file_put_contents call is used here only to keep the result for the next example.

An existing archive can be opened from a string as well, by passing it to openString:

<?php

$data = file_get_contents('archive.zip');

$zip = new ZipArchive();
$zip->openString($data);

echo $zip->numFiles.PHP_EOL; // 2
echo $zip->getFromName('hello.txt').PHP_EOL; // Hello
echo $zip->getFromName('data.json').PHP_EOL; // {"name":"John"}

The archive is opened from a string rather than from a path, which is useful when it arrives from an HTTP response or a database column.

Leave a Comment

Cancel reply

Your email address will not be published.