How to unzip a file using PHP ?

To unzip a file with PHP, we can use the ZipArchive class. ZipArchive is a simple utility class for zipping and unzipping files. We don’t require any extra additional plugins for working with zip files. ZipArchive class provides us a facility to create a zip file or to extract the existing zip file. The ZipArchive class has a method called extractTo to extract the contents of the complete archive or the given files to the specified destination. The ZipArchive class also has a lot of other methods and properties to help you get more information about the archive before extracting all its contents.

Syntax:

bool ZipArchive::extractTo( string $destination, mixed $entries )

Parameters:

  • destination: The $destination parameter can be used to specify the location where to extract the files.
  • entries: The $entries parameter can be used to specify a single file name which is to be extracted, or you can use it to pass an array of files.

Example 1: This example unzip all the files from specific folder.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$zip = new ZipArchive;
  
// Zip File Name
if ($zip->open('GeeksforGeeks.zip') === TRUE) {
  
    // Unzip Path
    $zip->extractTo('/Destination/Directory/');
    $zip->close();
    echo 'Unzipped Process Successful!';
} else {
    echo 'Unzipped Process failed';
}
?>

chevron_right


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



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

Example 2: This example unzip the specific file from the folder.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$zip = new ZipArchive;
  
// Zip File Name
$res = $zip->open('GeeksForGeeks.zip');
  
if ($res === TRUE) {
      
    // Unzip Path 
    $zip->extractTo('/Destination/Directory/',
        array('H_W.gif', 'helloworld.php'));
          
    $zip->close();
    echo 'Unzipped Process Successful!';
} else {
    echo 'Unzipped Process failed';
}

chevron_right


Description: With the file element, you can select the zip file that you want to extract. If a selected file is valid then pass to open() method and extract it to the specified path using extractTo() method.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.