Current Location: Home> Latest Articles> Complete Process of Using zip_entry_filesize from Opening a ZIP File to Getting File Size

Complete Process of Using zip_entry_filesize from Opening a ZIP File to Getting File Size

M66 2025-06-22

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.


1. Preparing: Opening the ZIP File

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.


2. Iterating through Files in the ZIP Archive

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";
}
?>

3. Opening Specific Entries and Getting File Size

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";
}
?>

4. Full Example

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);
?>


5. Conclusion

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.