Introduction
Zip is a very common and the most popular data compression format. Most of the files are sent and received in zip format. It is a very useful format for combining and compressing multiple files together. In PHP it is very easy to work with zip files. PHP provides functions for all the common operations on zip files like creating a zip archive, adding files to the archive, viewing the contents of the archive, and extracting its contents. This article is a simple demonstration of the zipping capabilities in PHP.
Using the ZipArchive class
In this article, we will explore the common operations on zip files supported in PHP using the ZipArchive class. The ZipArchive instance represents a file compressed in the zip format.
Following are some of the zip operations supported by PHP,
Viewing the names of entries in a zip file
To view the names of entries in a zip file, we need to first create an object of the ZipArchive class and invoke the open() function passing the zip file name as a parameter. The numFiles property can be used to know the number of files in the archive. The getNameIndex() method returns the name of an entry in the zip file using its index
- echo "Contents of $filename<br/>";
- $zip = new ZipArchive;
- if ($zip - > open($filename)) {
- echo "<ol>";
- for ($i = 0; $i < $zip - > numFiles; $i++) {
- echo "<li>".$zip - > getNameIndex($i).
- "</li>";
- }
- echo "</ol>";
- $zip - > close();
- }


Viewing the contents of files within a zip file
To view the contents files within a zip file, we need to first create an object of the ZipArchive class and invoke the open() function passing the zip file name as a parameter. The numFiles property can be used to know the number of files in the archive. The getNameIndex() method returns the name of an entry in the zip file using its index. The getFromIndex() method returns the file contents using its index. The following sample code can be used to view all the file names and their contents in a zip archive by iterating over all files.




Join the conversation! Your thoughts help the community grow.