How to create a zip file in PHP

Howdy!

I will show you how to create a zip file in PHP. All the directory in your server will also be zipped in the code. I will use the┬áZipArchive class in php. It’s easy as 1 2 3 :)

function ListFiles($dir) {
	if($dh = opendir($dir)) {
		$files = Array();
		$inner_files = Array();
		while($file = readdir($dh)) {
			if($file != "." && $file != ".." && $file[0] != '.') {
				if( $dir == getcwd() )	continue;
				if(is_dir($dir . "/" . $file)) {
					$inner_files = ListFiles($dir . "/" . $file);
					if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
				} else {
					array_push($files, $dir . "/" . $file);
				}
			}
		}

		closedir($dh);
		return $files;
	}
}

$zip = new ZipArchive();
$backupName = date("Y-M-d-h:i:a",time());
$filename = $backupName.".zip";
#Store the backup file in a Folder called 'Files'
if( $zip->open("Files/".$filename,ZIPARCHIVE::CREATE) !== TRUE ) {
	exit("Cannot open the archive file");
}
#Replace this one with your root directory
$directory = '/home/mysite/public_html';
foreach (ListFiles($directory) as $key=>$file){
        #do not include the backup files to be backed-up 
	if( strstr($file,getcwd()) != "" ) continue; 
	$zip->addFile($file);
}  
$zip->close();

To download the zip file, just access it through your browser, so mine is I put the zip file in a File Directory, so it should be something like this: http://mysite.com/File/ . It really depends.

Hope this helps someone! Have a happy coding!

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>