Hello, Today i'll explain you, how can we download multiple files with ZIP in Magento.
To download any file in Magento usually we used simple flow of Magento with controller method, but we get confuse while we need to download multiple files at same time. To download multiple files at same in download request we should use ZIP method, which will include all the files which allows to download.
Here is the code and code explanation to use ZIP method in Magento to download multiple files.
if(!extension_loaded('zip')){ Mage::log("Zip Extension does not loaded"); return false; }
Check whether ZIP extension is enabled in PHP or not, If extension is not enabled then it will log a message.
$destinationDir = Mage::getBaseDir('media'). DS . 'tempZipDir'; if(!is_dir($destinationDir)){ @mkdir($destinationDir); }
Set a destination directory path to save zip file to temporary. check if temp directory is exist or not, If not then create a temp directory.
$zip = new ZipArchive();
Create a ZipArchive object.
$zipFileName = 'someZipFileName_ ' . time(); $destinationDir = $destinationDir . DS . $zipFileName . '.zip';
Give some name to Zip file.
if(!$zip->open($destinationDir, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)){ Mage::log("Zip Archive Could not create"); return false; }
Try to create Zip file if it fail then set log message.
Now add files to ZipArchive which you want to send in download.
foreach($someFilePathArray as $filePath){ $fileContent = str_replace(array('/','\\'), DIRECTORY_SEPERATOR, realpath($filePath)); $baseFileName = substr($fileContent, strpos($fileContent, DIRECTORY_SEPERATOR) + 1); /** Clear file path and set base file name */ $result = $zip->addFile($fileContent, $baseFileName); }
$zip->close();
Close Zip file after adding files to ZipArchive.
if(file_exists($destinationDir)){ $downloadContent = file_get_contents($destinationDir); @unlike($destinationDir); $fileName = basename($destinationDir); $this->_prepareDownloadRespose($fileName, $downloadContent); }
Download with default controller method.