Thursday, September 4, 2025
HomeLanguagesHow to unzip a file using PHP ?

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.




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


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.




<?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';
}


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.

RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6625 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6694 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS