Skip to content

Instantly share code, notes, and snippets.

@sohelrana820
Last active May 7, 2023 19:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sohelrana820/95a37a475cf00580efe0347ee384152d to your computer and use it in GitHub Desktop.
Save sohelrana820/95a37a475cf00580efe0347ee384152d to your computer and use it in GitHub Desktop.
Create and download ZIP file in PHP
<?php
/**
* @author: Sohel Rana <me.sohelrana@gmail.com>
* @author URI: http://sohelrana.me
* @description: Create zip file and download in PHP
*/
function createZipAndDownload($files, $filesPath, $zipFileName)
{
// Create instance of ZipArchive. and open the zip folder.
$zip = new \ZipArchive();
if ($zip->open($zipFileName, \ZipArchive::CREATE) !== TRUE) {
exit("cannot open <$zipFileName>\n");
}
// Adding every attachments files into the ZIP.
foreach ($files as $file) {
$zip->addFile($filesPath . $file, $file);
}
$zip->close();
// Download the created zip file
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename = $zipFileName");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$zipFileName");
exit;
}
// Files which need to be added into zip
$files = array('sample.php', 'sample.jpg', 'sample.pdf', 'sample.doc');
// Directory of files
$filesPath = '/ROOT/FILE_PATH';
// Name of creating zip file
$zipName = 'document.zip';
echo createZipAndDownload($files, $filesPath, $zipName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment