How to Extract the Zip file with PHP

You don’t need to require any other extra plugin for working with Zip files.

PHP has a ZipArchive class that allows us to create a zip file or extract the existing file.

ZipArchive class extractTo() method is used to extract the zip file that takes the destination absolute path as an argument.

How to extract the Zip file with PHP


Contents

  1. On the same directory
  2. Specific file
  3. Conclusion

1. On the same directory

I am assuming the Zip file is stored in the project root directory.

Create an object of the ZipArchive class and open the given zip file using $zip->open() method.

If it returns TRUE then extract the file to the specified path ($path) with extractTo() method by passing path value as an argument in it.

Here, I am extracting the file in project files directory.

Completed Code

// Get Project path
define('_PATH', dirname(__FILE__));

// Zip file name
$filename = 'zipfile.zip';
$zip = new ZipArchive;
$res = $zip->open($filename);
if ($res === TRUE) {

  // Unzip path
  $path = _PATH."/files/";

  // Extract file
  $zip->extractTo($path);
  $zip->close();

  echo 'Unzip!';
} else {
  echo 'failed!';
}

2. Specific file

With file element, you can select the zip file that you want to extract.

If a selected file is valid then pass $_FILES['file']['tmp_name'] to open() method and extract it to specified path using extractTo() method.

Completed Code

<?php 
// Get Project path
define('_PATH', dirname(__FILE__));

// Unzip selected zip file
if(isset($_POST['unzip'])){
 $filename = $_FILES['file']['name'];

 // Get file extension
 $ext = pathinfo($filename, PATHINFO_EXTENSION);

 $valid_ext = array('zip');

 // Check extension
 if(in_array(strtolower($ext),$valid_ext)){
  $tmp_name = $_FILES['file']['tmp_name'];

  $zip = new ZipArchive;
  $res = $zip->open($tmp_name);
  if ($res === TRUE) {

   // Unzip path
   $path = _PATH."/files/";

   // Extract file
   $zip->extractTo($path);
   $zip->close();

   echo 'Unzip!';
  } else {
   echo 'failed!';
  }
 }else{
  echo 'Invalid file';
 }
 
}
?>
<form method='post' action='' enctype='multipart/form-data'>
 
 <!-- Unzip selected zip file -->
 <input type='file' name='file'><br/>
 <input type='submit' name='unzip' value='Unzip' />
</form>

3. Conclusion

Using the above PHP script you can extract the existing zip files at the specified location. For this, you need to pass the absolute path in extractTo() method of ZipArchive Class.

If you found this tutorial helpful then don't forget to share.

Leave a Comment