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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$files_to_zip = array(
  'preload-images/1.jpg',
  'preload-images/2.jpg',
  'preload-images/5.jpg',
  'kwicks/ringo.gif',
  'rod.jpg',
  'reddit.gif'
);
 
$filenames_in_zip = array(
  'preload-images/1.jpg',
  'images/2.jpg',
  'preload-images95.jpg',
  'ringo.gif',
  'rod/rod.jpg',
  'reddit/12/reddit.gif'
);
 
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip, $filenames_in_zip, 'down/my-archive.zip');

The function accepts an array of files, their respective names, the name of the destination zip folder to be saved at and a file overwriting condition.

Good luck!!!

Leave a Reply