When working with ZIP files in PHP, the zip_entry_filesize function is an essential tool for retrieving the size of a specific file within the archive. This article will detail the entire process from opening a ZIP file to using zip_entry_filesize to get the file size, with code examples to help you understand the workflow.
To operate on a ZIP file, you first need to open the archive. The zip_open function in PHP is commonly used to open a ZIP file, returning a resource handle.
<?php
$zipFile = 'http://m66.net/example.zip'; // Using the example domain m66.net
<p>$zip = zip_open($zipFile);</p>
<p>if ($zip === FALSE) {<br>
die('Unable to open the ZIP file');<br>
}<br>
?><br>
Note: zip_open supports both local file paths and some remote files. However, it is recommended to download remote files to the local system first before operating on them.
After opening the ZIP file, you need to iterate through the entries (files or folders) within the archive. You can use the zip_read function to fetch the next entry.
<?php
while ($entry = zip_read($zip)) {
$filename = zip_entry_name($entry);
echo "Filename: {$filename}\n";
}
?>
To retrieve the file size, you need to first open the entry using zip_entry_open, and then use zip_entry_filesize to get the size. Afterward, close the entry.
<?php
if (zip_entry_open($zip, $entry)) {
$filesize = zip_entry_filesize($entry);
echo "File Size: {$filesize} bytes\n";
zip_entry_close($entry);
} else {
echo "Unable to open entry\n";
}
?>
Here is a complete example that combines all the steps, showing how to open a ZIP file and get the size of each file inside:
<?php
$zipFile = 'http://m66.net/example.zip'; // Remote ZIP example
<p>$zip = zip_open($zipFile);</p>
<p>if ($zip === FALSE) {<br>
die('Unable to open the ZIP file');<br>
}</p>
<p>while ($entry = zip_read($zip)) {<br>
$filename = zip_entry_name($entry);<br>
echo "Filename: {$filename}\n";</p>
$filesize = zip_entry_filesize($entry);
echo "File Size: {$filesize} bytes\n";
zip_entry_close($entry);
} else {
echo "Unable to open entry\n";
}
echo "--------------------\n";
}
zip_close($zip);
?>
Use zip_open to open the ZIP file resource.
Use zip_read to iterate through all entries.
Open specific file entries with zip_entry_open.
Get the file size with zip_entry_filesize.
Close the entry using zip_entry_close and the ZIP file with zip_close.
With this, you have completed the full process of opening a ZIP file and getting the file sizes using PHP's native zip functions.
If you need precise control and low-level operations when handling ZIP files, the above methods are very practical options.