Master PHP’s zip_read(): Read ZIP Entries Efficiently

This guide explains how to use PHP’s zip_read() function to open a ZIP archive, iterate through its entries, retrieve each entry’s name and size, and properly close the archive, while noting its limitations and related extraction functions.

php Courses
php Courses
php Courses
Master PHP’s zip_read(): Read ZIP Entries Efficiently
zip_read()

is a PHP function that reads the next entry from an opened ZIP archive and returns its details.

Syntax

zip_read(resource $zip)

The $zip parameter is a ZIP file resource returned by zip_open(). zip_read() returns a resource containing entry details or false when no more entries are available.

Usage Steps

Open the ZIP file

$zip = zip_open('path/to/zipfile.zip');

Check if the ZIP file opened successfully

if ($zip) {
    // continue processing
} else {
    // handle error
}

Loop through entries

while ($zip_entry = zip_read($zip)) {
    // process each entry
}

Close the ZIP file

zip_close($zip);

Inside the loop, each call to zip_read() returns the next entry, stored in $zip_entry. Use zip_entry_name() to get the entry name, zip_entry_filesize() for its size, etc.

Example: read all entries and output their names and sizes.

$zip = zip_open('path/to/zipfile.zip');
if ($zip) {
    while ($zip_entry = zip_read($zip)) {
        $name = zip_entry_name($zip_entry);
        $size = zip_entry_filesize($zip_entry);
        echo "Name: $name, Size: $size bytes
";
    }
    zip_close($zip);
} else {
    echo "Failed to open ZIP file
";
}

Note that zip_read() only reads entry metadata; it does not extract files. To extract, use functions such as zip_entry_open() and zip_entry_read().

In summary, zip_read() is a useful PHP function for retrieving information about ZIP entries, facilitating further processing.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPFile Processingzip_readZIP handling
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.