Current Location: Home> Latest Articles> How to Determine the File Size Inside a ZIP Archive Using PHP's ZipArchive Class

How to Determine the File Size Inside a ZIP Archive Using PHP's ZipArchive Class

gitbox 2025-06-17

Overview

PHP’s ZipArchive class is a powerful tool for developers, allowing the creation, modification, and extraction of ZIP archives. In many real-world scenarios, you may need to determine the file size of files inside a ZIP archive, particularly when working with large files. This helps prepare for processing or ensuring efficient resource management. This article will show you how to use PHP’s ZipArchive class to retrieve and check file sizes inside a ZIP archive.

Step 1: Open the ZIP Archive

First, we need to create a ZipArchive object and use the `open` method to open a ZIP archive. Here’s an example:
$zip = new ZipArchive;
if ($zip->open('path/to/your/archive.zip') === true) {
    // Archive opened successfully
} else {
    // Failed to open the archive
}

Step 2: Retrieve File Information

Next, we can use the `statIndex` method to get detailed information about a file at a given index, including its name, size, and other attributes. Here’s the code to get the size of the first file:
$fileInfo = $zip->statIndex(0); // Get info of the first file
$fileSize = $fileInfo['size']; // Get file size

Step 3: Retrieve File Name

You can also use the `getNameIndex` method to get the name of the file at a given index. Here’s an example for retrieving the name of the first file:
$fileName = $zip->getNameIndex(0); // Get the name of the first file

Step 4: Loop Through All Files in the Archive

If you need to loop through all files in the archive and print out their names and sizes, you can refer to the following complete example:
$zip = new ZipArchive;
if ($zip->open('path/to/your/archive.zip') === true) {
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $fileInfo = $zip->statIndex($i);
        $fileName = $zip->getNameIndex($i);
        $fileSize = $fileInfo['size'];
        echo "File Name: $fileName, File Size: $fileSize bytes";
    }
    $zip->close();
} else {
    echo 'Failed to open the archive';
}

Important Notes

  1. Make sure the PHP Zip extension is enabled before using the ZipArchive class.
  2. Ensure that the archive has been successfully opened before reading files from it.
  3. The code example provided loops through only the first file in the archive. To loop through all files, modify the loop conditions accordingly.

Conclusion

By using PHP’s ZipArchive class, you can easily determine the file size of files within a ZIP archive. This is crucial when working with large files or when you need to process archives efficiently. Mastering these techniques will help you handle file compression and extraction tasks more effectively during development.