Download Directory as Zip Archive Using Php function

Some times we have to need our wordpress plugin directory or any other directiory  at a time archive to zip using php function.In that case just simply call a function to do  download directory as zip archive.

Here is the following code:

 

function download_directiory(){
//Get the plugin folder
$rootPath = plugin_dir_path( __FILE__ ) ;
// Initialize zip archive object
$zip = new ZipArchive();
// location to download file archive
$archive = plugin_dir_path( __FILE__ ).'assets/test.zip';
$res = $zip->open($archive, ZipArchive::CREATE);
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
if (!$file->isDir())
{
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath));
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}

// Zip archive will be created only after closing object
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
@set_time_limit(0);
die();
}

Hopefully it will helps you.