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.
