Wednesday, April 11, 2018

How to unzip or extract zip file using PHP

This post explains how to unzip or extract a folder using PHP with the help of ZipArchive class. ZipArchive is a built in class of PHP and was introduced in PHP version 5.2 . This class will help you to unzip, zip or read zip file.

How to unzip or extract zip file using PHP


Recently we have posted a tutorial for creating a zip file using php and i think you should read about it to build more understanding on zip file creation process. In case of any questions, please do comment in comment box below.


Unzip a zip file using ZipArchive Class

Lets see the complete example to unzip a file using ZipArchive Class.

Step-1 :
creates an object of the ZipArchive class.
$zip = new ZipArchive();

Step-2 :
opening the zip file using open() function.
$zip->open($source)

Step-3 :
Set the destination for the zip file extraction.
$destination = 'extracted/';
$zip->extractTo($destination);

Step-4: 
closing the zip file.
$zip->close();

Complete Source Code :
This script will help you extract files from the existing zip file. Here we are extracting the files from "skptricks-zip.zip" zip file.

unzip-file-using-php.php
<?php
  //Check whether zip extension is enabled or not
  if(extension_loaded('zip')) {
    $zip = new ZipArchive();
    
    //Path of the source zip file to be extracted
    $source = "skptricks-zip.zip";
    if ($zip->open($source) == TRUE) { 
      //Destination of extracted files and folders to be stored
      $destination = 'extracted/';
      $zip->extractTo($destination);
      $zip->close();
    } else {
      echo "Failed to open the zip file!";
    }
  } 

?>


Download Link :
https://github.com/skptricks/php-Tutorials/tree/master/How%20to%20unzip%20or%20extract%20zip%20file%20using%20PHP

This is all about unzip or extract zip file using PHP. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.



No comments:

Post a Comment