In PHP, zip_read() is a function used to read entries within a ZIP archive. It is typically used in conjunction with zip_open(), which allows developers to traverse various file or directory entries within the ZIP file, enabling operations and processing on the compressed package.
resource zip_read(resource $zip);
Parameter Description:
$zip: The ZIP resource handle returned by zip_open().
Return Value:
Returns a resource handle pointing to a ZIP entry on success.
Returns false on failure.
zip_read() has only one parameter, which is the ZIP resource handle. This handle is obtained after opening a ZIP file using the zip_open() function.
For example:
$zip = zip_open('http://m66.net/path/to/your.zip');
if (is_resource($zip)) {
while ($entry = zip_read($zip)) {
// Process $entry
}
zip_close($zip);
}
Typically, we use zip_read() in combination with other functions to read files within a ZIP file. For example:
zip_entry_name() retrieves the name of the current entry.
zip_entry_filesize() retrieves the size of the current entry.
zip_entry_open() opens the current entry to read its contents.
zip_entry_read() reads the content of the entry.
zip_entry_close() closes the current entry.
Example code is as follows:
$zip = zip_open('http://m66.net/files/example.zip');
if (is_resource($zip)) {
while ($entry = zip_read($zip)) {
$name = zip_entry_name($entry);
echo "File Name: $name\n";
$size = zip_entry_filesize($entry);
$contents = zip_entry_read($entry, $size);
echo "File Contents:\n$contents\n";
zip_entry_close($entry);
}
}
zip_close($zip);
} else {
echo "Unable to open ZIP file";
}
In this example:
The ZIP file located at http://m66.net/files/example.zip is opened using zip_open().
All entries are looped through using zip_read().
Entry names are output using zip_entry_name().
The contents of entries are read using zip_entry_open() and zip_entry_read().
Entries and ZIP resources are closed.
zip_read() depends on zip_open(), so the ZIP file resource must be successfully opened first.
To read remote ZIP files, the PHP directive allow_url_fopen must be enabled.
This function is suitable for sequential reading of a ZIP file, but not for random access of entries.
If you only need to list file names, skip reading the content to avoid performance overhead.