Last active
October 15, 2024 11:37
-
-
Save sohelrana820/95a37a475cf00580efe0347ee384152d to your computer and use it in GitHub Desktop.
Create and download ZIP file in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author: Sohel Rana <[email protected]> | |
* @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