Skip to content

How to Unpack a Zip File using PHP?

Last updated on November 28, 2022

In this post, I will show you how easily we can unzip a zip file using PHP. I am gonna show you most simplest method , with PHP’s built-in function system(). which executes an external program and displays the output.

Unzip using the system function.

<?php system('unzip file.zip'); ?>

Above line of script will unpack the file.zip file, in the same directory.

On some shared hosting environments system() function may not be available(security reasons). In that case use ZipArchive. ZipArchive is PHP’s built-in extensions for dealing with compressed files.

Unzip using ZipArchive

<?php
// zip file path.
$file = file.zip; 
//create an instance of ZipArchive Class
$zip = new ZipArchive;

//open the file that you want to unzip. 
//NOTE: give the correct path. In this example zip file is in the same folder
$zipped = $zip->open($file);
 
// get the absolute path to $file, where the files has to be unzipped
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
 
//check if it is actually a Zip file
if ($zipped) {

//if yes then extract it to the said folder
  $extract = $zip->extractTo($path);
 
  //if unzipped succesfully then show the success message
  if($extract){
    echo "Your file extracted to $folder_name";
  } else {
    echo "your file not extracted";
  }

  //close the zip
  $zip->close();  
}

Note: This script works only If the ZIP extension installed in your PHP server.

That’s it

5 1 vote
Article Rating
Subscribe
Notify of
guest

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments