Current Location: Home> Latest Articles> How to Use PHP ZipArchive to Check File Compression Rates in ZIP Archives

How to Use PHP ZipArchive to Check File Compression Rates in ZIP Archives

M66 2025-06-22

How to Check File Compression Rates in ZIP Archives Using PHP ZipArchive

When working with ZIP files in web development, it's often useful to analyze the compression efficiency of each file in the archive. This helps evaluate performance and optimize storage. PHP’s built-in ZipArchive class provides a convenient way to inspect compressed files and calculate their compression rates.

Initializing ZipArchive and Opening a ZIP File

First, you need to create a ZipArchive object and open an existing ZIP file:


$zip = new ZipArchive;
$zipFile = 'path/to/archive.zip';

if ($zip->open($zipFile) === true) {
    // Logic to analyze compression rates goes here
} else {
    echo 'Unable to open ZIP file';
}

Iterating Through Files and Calculating Compression Rates

Once the ZIP file is opened, you can loop through its contents, retrieve the original and compressed sizes, and compute the compression percentage for each file:


$totalSizeBefore = 0;
$totalSizeAfter = 0;

for ($i = 0; $i < $zip->numFiles; $i++) {
    $fileName = $zip->getNameIndex($i);
    $stat = $zip->statIndex($i);
    $sizeBefore = $stat['size'];
    $sizeAfter = $stat['comp_size'];

    $totalSizeBefore += $sizeBefore;
    $totalSizeAfter += $sizeAfter;

    $compressionRate = ($sizeBefore - $sizeAfter) / $sizeBefore * 100;

    echo "Filename: {$fileName}<br/>";
    echo "Original Size: {$sizeBefore} bytes<br/>";
    echo "Compressed Size: {$sizeAfter} bytes<br/>";
    echo "Compression Rate: {$compressionRate}%<br/>";
    echo "<br/>";
}

$averageCompressionRate = ($totalSizeBefore - $totalSizeAfter) / $totalSizeBefore * 100 / $zip->numFiles;

echo "Total Original Size: {$totalSizeBefore} bytes<br/>";
echo "Total Compressed Size: {$totalSizeAfter} bytes<br/>";
echo "Average Compression Rate: {$averageCompressionRate}%<br/>";

$zip->close();

Explanation and Use Case

In the example above, two total size variables track the sum of all files before and after compression. The script calculates each file’s individual compression rate and outputs an average rate at the end.

Note that this method is only suitable for analyzing already-created ZIP files. If you're generating ZIP files and want to estimate compression rates in advance, you can read the file content using file_get_contents and compress it with gzcompress to simulate the compression process.

Conclusion

By using the methods provided by PHP’s ZipArchive class, you can efficiently inspect compression rates of files within a ZIP archive. This is especially helpful for optimizing storage and evaluating compression strategies in your applications.