Extract the Zip file with PHP

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

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

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

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 directory.

Create an object of the ZipArchive class and open 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 your zip file that you want to extract.

If select 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['unzip2'])){
 $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='unzip2' value='Unzip2' />
</form>

 

3. Conclusion

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

Related Post

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *