Creating a zip file using php

Creating a zip file in php is as easy as creating them on your desktop using some zipping software. Php comes with inbuilt class that helps in making a zip file and provides all the functionality that you would ever need. Here is a simple function that I coded for my project. Hope it helps some peoples out there as well.

Php code:

// creates a compressed zip file
function create_zip($files = array(), $filename=array(), $destination = '',$overwrite = false) {
	//if the zip file already exists and overwrite is false, return false
	if(file_exists($destination) && !$overwrite) { return false; }

	//vars
	$valid_files = array();
	$valid_names = array();
	$i=0;

	//if files were passed in...
	if(is_array($files)) {
		//cycle through each file
		foreach($files as $file) {
			//make sure the file exists
			if(is_file($file)) {
				$valid_files[] = $file;
				if(isset($filename[$i]) && $filename[$i]!='') {
					$valid_names[]=$filename[$i];
				} else {
					$valid_names[]=$file;
				}
			}
			$i++;
		}
	}

	//if we have good files...
	if(count($valid_files)) {
		//create the archive
		$zip = new ZipArchive();
		if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}

		$i=0;
		//add the files
		foreach($valid_files as $file) {
			$zip->addFile($file,$valid_names[$i]);
			$i++;
		}

		//debug
		//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

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

		//check to make sure the file exists
		return file_exists($destination);
	} else {
		return false;
	}
}

Usage demo:

Continue reading “Creating a zip file using php”