Create zip archive with php

In php creating zip file is very easy. PHP 5.2 has an inbuilt class ZipArchive to manipulate zip file, if you are using a older version of php then you can install PECL zip on your server. To make this task more handy I have created a simple function to make zip archive that anyone can use in their web application.

function createZIP($files = array(),$output = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($output) && !$overwrite) { return false; }

$zip = new ZipArchive();
if($zip->open($output,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
if(count($files))
{
//add the files to zip
foreach($files as $file) {
$zip->addFile($file,$file);
}

//close the zip
$zip->close();

//check to make sure the output zip file creaded and exists
return file_exists($output);
}
else
{
return false; //no files provided to create zip file
}
}

Usage example

$files_to_zip = array(
	'file1.txt',
	'image.jpg',
	'file2.text',
	'dir/some.text'
);
//if true, good; if false, zip creation failed
$result = createZIP($files_to_zip,'myArchive.zip');

createZIP function accepts array of files to archive in zip, output file name and whether or not to overwrite a output file if it already exists. This function returns Boolean true on success and false on fail.


Liked It? Get Free updates in your Email

Delivered by feedburner

Leave a Reply

Your email address will not be published. Required fields are marked *