Current Location: Home> Latest Articles> What is the basic syntax of the zip_read() function? What are its parameters and specific usage?

What is the basic syntax of the zip_read() function? What are its parameters and specific usage?

M66 2025-06-23

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.


1. Basic Syntax of the zip_read() Function

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.


2. Parameter Details

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

3. Specific Usage

Typically, we use zip_read() in combination with other functions to read files within a ZIP file. For example:

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:

  1. The ZIP file located at http://m66.net/files/example.zip is opened using zip_open().

  2. All entries are looped through using zip_read().

  3. Entry names are output using zip_entry_name().

  4. The contents of entries are read using zip_entry_open() and zip_entry_read().

  5. Entries and ZIP resources are closed.


4. Important Notes

  • 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.