How to extract a zip file in php



In previous tutorial I have explained how to create a zip file in PHP. It is useful for create a zip file of selected documents and download it in zip format. Now in this tutorial I will explain how to extract a zip file in PHP. It will help us to take zip file from the user directly and extract them for use easily.

We will use php class ZipArchive, but that need ZIP extension to available. We need too pass the path of the file to open and where we need to extract the file. Create a file extract.php and write following code.

error_reporting(1);

$zip_filename = "pi.zip";
$path = dirname(__FILE__)."/files/";

$zip = new ZipArchive;
$res = $zip->open($path.$zip_filename);

if ($res === TRUE) {

	$zip->extractTo($path);
	$zip->close();
	echo 'Zip extracted';
} else {
	echo 'try again';
}

This is an simple example of how yo extract a zip file in PHP.

ZipArchive::open – Opens a new zip archive for reading, writing or modifying.

ZipArchive::extractTo – Extract the complete archive or the given files to the specified destination.

Hope this tutorial will help you.