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

- by

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 '

There was a problem writing the ZIP archive.

'; } else { echo '

Successfully created the ZIP Archive!

'; }

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.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.