Back to Top

How to Create a Zip File In PHP

Before Some days, I have created one function with the use of zip archive class in PHP.For one site, I want to create the zip file of all documents generated in one directory. so the user can download all documents via a single zip file and for that I have used Zip Archive Class of PHP So let’s start it!

Zip file is a compressed file which can mainly store as .zip extension and its well-known compression format to gather data and its very simple with PHP with Zip Archive class

How To create zip File using PHP

Let’s see one example which shows you how to create the zip file.Here, I have created one function which create the zip file.

function Create_zip($source, $destination,$overwrite='')
{
	$zip = new ZipArchive();
	if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE) === TRUE)
	{
		$zip->addFile($source);// Add the files to the .zip file
		$zip->close(); // Closing the zip file
	}
}
Create_zip("file.php","Compressed.zip");

How To extract zip File using PHP

Now, Let’s see how to extract zip file

function Extract_zip($source, $destination)
{
	$zip = new ZipArchive(); // Call object of ZipArchive
	if ($zip->open($source) === TRUE) // Open Compressed.zip for extracting all files
	{
		$destination = str_replace('\', '/', realpath($destination));
		// Will extract all files from master.zip to given path.
		$zip->extractTo($destination);
		$zip->close();
     }
}
Extract_zip("Compressed.zip", 'link/');

How to Zip a directory in PHP?

Up to now, We have checked how to zip and unzip file but now let’s see how to zip the whole directory which contain multiple files.

public function create_zip($source,$destination,$overwrite=’’)
{
	if (!extension_loaded('zip') || !file_exists($source)) {
		return false;
	}
	$zip = new ZipArchive();
	$source = str_replace('\', '/', realpath($source));
	// to replace path of path to real path
	if (is_dir($source) === true)
	{
		$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source),RecursiveIteratorIterator::SELF_FIRST);
		foreach ($files as $file)
		{
			$file = str_replace('\', '/', realpath($file));
			$ext = substr(strrchr($file,'.'),1); 
			// To get extension of files in directory
			if($ext=='zip')
			{
				unlink($file);
				// if overwrite file,its overwrite zip folder
				// also within a directory so will unlink it
				continue;
			}
		}
		if (!$zip->open($destination,$overwrite?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE))
		{
			return false;
		}
		if (is_dir($source) === true)
		{
			$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source),
			RecursiveIteratorIterator::SELF_FIRST);
			//To find all the files (recursively) in a certain directory
			foreach ($files as $file)
			{
				if (is_dir($file) === true)
				{
				 $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
			   }
			   else if (is_file($file) === true)
			   {
					$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
					//To add a file to a ZIP archive with the use of its contents
			   }
			}
		}
		else if (is_file($source) === true)
		{
			$zip->addFromString(basename($source),      file_get_contents($source));
		}
	return $zip->close();
	}
}

Above function first check that extension for zip is loaded or not, if not, return back to function with false. If loaded, it will create ZipArchive() object and fetch the source. RecursiveIteratorIterator will recursive check the existence of files in the directory and if any file has extension zip, it will be unlink or deleted. Again used same functions to check empty directory and string.

Also READ:

To Unzip file and move to destination in PHP
Cloning Object in PHP

I hope you have enjoyed this short post. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

Comments (2)

  1. Fully great stuff here.. Thanks!But if you can do some, maybe you should pidvroe us the web version.Its hard for me to translate all the elements into HTML.Oooh.. I’m a web designer and really hoping I can see the web version for this one, or for the entire stuff here maybe..Thanks.

  2. Great and details article. I am using this simple snippet for unzip
    $zip = new ZipArchive;
    $res = $zip->open($filename); // Your filename
    if ($res === TRUE) {
    $zip->extractTo(‘./’);
    $zip->close();
    }

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

What is JavaScript Hoisting

Posted on 3 years ago

Bhumi

Sliding Thumbnail and Caption with jQuery

Posted on 6 years ago

Bhumi

To get Last auto increment id in WordPress

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2015

Posted on 3 years ago

Bhumi

The Reader’s Poll – August 2014

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 4 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 4 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 5 years ago

Bhumi