How To Download & Extract Zip Archives in PHP

PHP

If you used WordPress before, you know that when you do plugin installation action, WordPress automatically downloads and extract the plugin zip file. If you’re app needs something like this, you will find this post useful.

PHP has the Zip Archive Extension. You can see the php manual for installing ZipArchive Extension. The usage of ZipArchive extension is very easy.

Download

For downloading, we will use cURL. First we create a blank zip file, download the zip file from server and put it’s contents to the blank zip file we created.

$url = "http://example.com/pathtozipfile.zip";
$zipFile = "folder/zipfile.zip"; // Local Zip File Path
$zipResource = fopen($zipFile, "w");
// Get The Zip File From Server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_FILE, $zipResource);
$page = curl_exec($ch);
if(!$page) {
 echo "Error :- ".curl_error($ch);
}
curl_close($ch);

cURL will get the Zip archive file from url mentioned in the variable $url. The $zipFile variable contain the local path of the file were we’re going to save the Zip archive file.

Extract (Unzip)

For extracting as we mentioned before, we will use the PHP Zip Archive Extension.

We’ll make the class variable, open the Zip archive file and extract it :

/* Open the Zip file */
$zip = new ZipArchive;
$extractPath = "path_to_extract";
if($zip->open($zipFile) != "true"){
 echo "Error :- Unable to open the Zip File";
} 
/* Extract Zip File */
$zip->extractTo($extractPath);
$zip->close();

The extract path should be mentioned in the $extractPath variable. If any of the files exists, it will be overwritten or merged.

If any of the above code doesn’t work, check if the directory permission is set to Read & Write and if the problem still exists, please post a comment and I will be delighted to help you.