I have one application that upload some files and then I can compress as zip file and download.
The export action:
public function exportAction() {
ZipArchive creates the zip file into the root directory of your website if only a name is indicated into open
function like $zip->open("document.zip", ZipArchive::CREATE)
. Specify the path into this function like $zip->open("my/path/document.zip", ZipArchive::CREATE)
. Do not forget delete this file with unlink()
(see doc).
Here you have an example in Symfony 4 (may work on earlier version):
use Symfony\Component\HttpFoundation\Response;
use \ZipArchive;
public function exportAction()
{
// Do your stuff with $files
$zip = new ZipArchive();
$zip_name = "../web/zipFileName.zip"; // Users should not have access to the web folder (it is for temporary files)
// Create a zip file in tmp/zipFileName.zip (overwrite if exists)
if ($zip->open($zip_name, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
// Add your files into zip
foreach ($files as $f) {
$zip->addFromString(basename($f), file_get_contents($f));
}
$zip->close();
$response = new Response(
file_get_contents($zip_name),
Response::HTTP_OK,
['Content-Type' => 'application/zip',
'Content-Disposition' => 'attachment; filename="' . basename($zip_name) . '"',
'Content-Length' => filesize($zip_name)]);
unlink($zip_name); // Delete file
return $response;
} else {
// Throw an exception or manage the error
}
}
You may need to add "ext-zip": "*"
into your Composer file to use ZipArchive
and extension=zip.so
in your php.ini
.
Answser inspired by Create a Response object with zip file in Symfony.