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 transfer.
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 ZipArchive class, you can simply create a zip file or to extract the existing zip file. It has various methods for zip files.
In this tutorial, we will take examples to Zip and Unzip files in PHP.
To unzip zip file, we will use extractTo() method provide by ZipArchive class. This function takes two parameter first is destination and second one is files. We will use second parameter when we want to extract specific files.
Let's take example to extract all files or specific files.
In above example, First of all we have created object of ZipArchive class then we try to open zip file and print message according to it. After that, we will use extractTo() method and pass destination folder as parameter. Use second way to extract specific files. Here, you can pass an array with name of files or directory.
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 into 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.
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.
Ask anything about this examples