Zip Current Directory and its contents recursively

This is a slightly modified version of one stackoverflow post. If the folder to be zipped is large the execution time may be larger than your current setting. So you may need to modify max_execution_time parameter.

<?php 	
$rootPath = getcwd(); 	
$zip = new ZipArchive(); 	
$filename = 'Archive.zip'; 	
$zip->open( $filename, ZipArchive::CREATE | ZipArchive::OVERWRITE);

	$files = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator($rootPath),
		RecursiveIteratorIterator::LEAVES_ONLY
	);

	foreach ($files as $name => $file)
	{
		if (!$file->isDir())
		{
			// Get real and relative path for current file
			$filePath = $file->getRealPath();
			$relativePath = substr($filePath, strlen($rootPath) + 1);
			// Add current file to archive
			$zip->addFile($filePath, $relativePath);
		}
	}
	$zip->close();
	header('Content-Type: application/zip');
    header("Content-Disposition: attachment; filename = $");
    header('Content-Length: ' . filesize($filename));
    header("Location: $filename");
?>

Advertisements