Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP compress/zip files with percentage progress bar - is it possible?

Trying to compress bunch of files using ZipArchive class. All is working fine, but I would like to have some kind of status bar with percentage zipped while users are waiting for zipping to be completed.

Is this even possible with ZipArchive? Are there any other zib libraries I could use to accomplish this?

Thanks!

like image 225
elveez Avatar asked Dec 07 '25 19:12

elveez


2 Answers

Adding files to the zip is usually fast. Usually the slowest process if you are zipping large number of files will be the $zip->close(). There is a new method in PHP zipArchive class: https://www.php.net/manual/en/ziparchive.registerprogresscallback.php

This will allow you monitor the progress of zip closing.

$zip = new ZipArchive();

if ($zip->open('php.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
    $zip->addFile(PHP_BINARY, 'php');

    $zip->registerProgressCallback(0.05, function ($r) {
        printf("%d%%\n", $r * 100);
    });

    $zip->close();
}

This seems to be available in PHP 8.0. I tested this with PHP 7.4+ and is not available there yet.

like image 126
Emerson Maningo Avatar answered Dec 10 '25 08:12

Emerson Maningo


Just note for who came here hoping to find a way to monitor progress for extractTo: This sadly doesn't work for extractTo as this method not executed on close.

like image 28
SomeOne_1 Avatar answered Dec 10 '25 08:12

SomeOne_1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!