Php zip a directory and automatically download
Posted Date:21-02-2017
This Post will explain how to download the directory using php.
Assumption value:
$sourecedir = 'images/';//this is an path of the folder name $zip_file = 'file.zip';//this is an downloadable zip foler name
There two variable $sourcedir and $zipfile, $sourcedir varible mention the folder and $zipfile mention downloadable folder name.
First Initialize archive object
$zip = new ZipArchive();// Initialize archive object> $zip = new ZipArchive(); $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
Second, Create Create recursive directory iterator is download all files with subfoler
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath) );
Third,Use foreach loop to add the file to archive
foreach ($files as $name => $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); $zip->addFile($filePath, $relativePath); } }
Finally,Close the zip and add zip header in php ,read the file
$zip->close(); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($zip_file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($zip_file)); readfile($zip_file);
If following all the steps and get final code like this
<?php $dir = 'target'; $zip_file = 'file.zip'; $rootPath = realpath($dir); $zip = new ZipArchive(); $zip->open($zip_file, ZipArchive::CREATE | ZipArchive::OVERWRITE); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath) ); foreach ($files as $name => $file) { if (!$file->isDir()) { $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); $zip->addFile($filePath, $relativePath); } } $zip->close(); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($zip_file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($zip_file)); readfile($zip_file); ?>