A few days ago, a client requested a contact form submission to go to an autoimporting email address in a specific format. At first, this wasn’t an issue – a CSV file was fine. However, the client wanted a zipped CSV. At first I thought this was going to be difficult – Linux + Zip? – but it turns out PHP has some nifty functions to create and add to zip files.

Looking into it a bit further it appears it isn’t brilliant – for example, there is a lack of support for NOT compressing the archive – but it did exactly what I required.

I put together a little function to take care of it and make it re-usable. Take a look below.

The solution function

protected function createZipFile($files = array(), $destination = '', $overwrite = false) {

	// sanity check
        if (file_exists($destination) && $overwrite === false) { return false; }

	// should probably add something to ensure that the files exist?

	if (count($files)) {
		$zip = new ZipArchive();
		if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}
    
		foreach($files as $file) {
			// use basename so that we don't keep the directory structure
			$zip->addFile($file, basename($file));
		}

		$zip->close();

		return true
	}
	else
	{
		return false;
	}
	
}

Making the call

$files_to_zip = array('path/image1.jpg', 'image2.jpg');
$destination = getcwd() . '/files/filename.zip';
$result = $this->createZipFile($files_to_zip, $destination);

Image Credit: Key Foster