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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s