How to create a recursive ZIP Archive from a directory in PHP

PHP-IconI’ve just realised how (relatively) easy it is to make PHP create a ZIP Archive from a directory and its sub directories.

Previously I had relied on the Linux Shell Command zip or tar to do this which is a convenient one liner. I had assumed that in PHP we had to go through each directory and add the files manually – until I’ve discovered the RecursiveIterator class variants.

In this example I’m defining a root path and a file name for my archive (change at will), then iterate through each file in each directory (and if thats’ a directory too, we’ll go one level deeper). The result of which is an array of files. We’ll get their full paths and add them to the ZIP archive.

// define some basics
$rootPath = './';
$archiveName = 'zipfile.zip';

// initialize the ZIP archive
$zip = new ZipArchive;
$zip->open($archiveName, ZipArchive::CREATE);

// create recursive directory iterator
$files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);

// let's iterate
foreach ($files as $name => $file) {
	$filePath = $file->getRealPath();
	$zip->addFile($filePath);
}

// close the zip file
if (!$zip->close()) {
	echo '<p>There was a problem writing the ZIP archive.</p>';
} else {
	echo '<p>Successfully created the ZIP Archive!</p>';
}

The above will produce a ZIP file which will contain references to the absolute full paths of each file. That’s great if you’d like to unzip those files later in exactly the same location – but it’s not so cool if you’re just interested in the content and the idea of 11 sub folders strikes you as “less funny”.

Help is at hand, thanks to the way we can add files to the archive – namely by creating a new local filename. Here’s an example of how this works on Linux systems:

// let's iterate and create a new local file name
foreach ($files as $name => $file) {
	$new_filename = substr($name,strrpos($name,'/') + 1);
	$zip->addFile($file, $new_filename);
}

No more references to absolute full paths in your ZIP file.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.