All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Download And Extract Zip File Using PHP

Last Updated : Jul 1, 2023

IN - PHP | Written & Updated By - Dikshita

In this tutorial we will show you how to download and extract Zip file using PHP.There are many times when you want to download zip file in your web application through URL and extract zip file to a particular folder on server side using PHP then this tutorial will be helpfull for you.

You may also like create zip file using PHP.

Download And Extract Zip File Using PHP

To Download And Extract Zip File It Takes Only One Step:-

  1. Make a PHP file to download and extract zip file

Step 1. Make a PHP file to download and extract zip file

We make a PHP file and save it with a name zip.php


$url = "http://anysite.com/file.zip";
$zip_file = "folder/downloadfile.zip";

$zip_resource = fopen($zipFile, "w");

$ch_start = curl_init();
curl_setopt($ch_start, CURLOPT_URL, $url);
curl_setopt($ch_start, CURLOPT_FAILONERROR, true);
curl_setopt($ch_start, CURLOPT_HEADER, 0);
curl_setopt($ch_start, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch_start, CURLOPT_AUTOREFERER, true);
curl_setopt($ch_start, CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch_start, CURLOPT_TIMEOUT, 10);
curl_setopt($ch_start, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch_start, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch_start, CURLOPT_FILE, $zip_resource);
$page = curl_exec($ch_start);
if(!$page)
{
 echo "Error :- ".curl_error($ch_start);
}
curl_close($ch_start);

$zip = new ZipArchive;
$extractPath = "Download File Path";
if($zip->open($zipFile) != "true")
{
 echo "Error :- Unable to open the Zip File";
} 

$zip->extractTo($extractPath);
$zip->close();

In this step we insert URL path to download zip file we insert all the details like folder to which we were going to save the file and file name.

We initialise curl to download the file and add all the proper headers to download file and then it save the zip file in that folder.

Now we come to our second part that is extract the downloaded zip file we create a new zip archive object then simply use open function to open zip file and extract the zip file to a particular folder by using extractTo() function.

You can also view create, edit and delete file using PHP.

That's all, this is how to download and extract Zip file using PHP.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

I hope this tutorial on php ziparchive helps you and the steps and method mentioned above are easy to follow and implement.