Compressing files when transferring them over the internet has a lot of advantages like it saves time and data transfer. With zip and unzip we can reduce file size and save lots of time while transferring.
PHP comes with a lot of extensions that deal specifically with file compression and extraction. While working in PHP, we don't require any extra plugins to compress or extract zip files. Using the ZipArchive class, you can simply create a zip file or extract the existing zip file. It has various methods for zip files.
In this tutorial, we will take examples of Zip and Unzip files in PHP.
Unzip Files
To unzip the zip file, we will use extractTo() method provided by the ZipArchive class. This function takes two parameters which are destination and files. We will use second parameter when we want to extract specific files.
Let's take an example to extract all files or specific files.
<?php
$zip = new ZipArchive;
if ($zip->open('images.zip') === TRUE) { //Zip file name
// To extract all files
$zip->extractTo('/uploads/images/'); //Destination location
//To extract specific file
$zip->extractTo('/uploads/images/', 'file.txt'); //Destination location
$zip->close();
echo 'Success';
} else {
echo 'Failed';
}
?>
In the above example, we have created an object of ZipArchive class then we try to open a zip file and print message according to it. After that, we will use extractTo() method and pass destination folder as a parameter. Use a second way to extract specific files. Here, you can pass an array with names of files or directories.
Create Zip File
We can add files to zip archive one at a time or add the whole directory at once. In either case, the first step is to create a new ZipArchive instance and then call the open() method.
In the above example, we have created a new object of the ZipArchive class. Then we opened our directory using the opendir command. For adding files to our zip archive we have to loop through all files of the selected directory and add them one by one. Lastly, the close method will close the ZipArchive object and creates a zip file in our file system.
Conclusion
In this article, we have compressed and extracted a zip file in PHP using ZipArchive class. Now You should be able to compress or extract individual files or a group of them at once as per your requirement.