0

Im currently developing a site where customers can download brand images like packshots. Ive made a custom cart where the client should be able to download all images added to the cart using ZipArchive. But it dosent seem to work as easy if it was not WordPress(as it usually is).

My code:

$files = array('test.jpg', 'test2.jpg');
$zipname = 'images.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

At first i had Error: Warning: Cannot modify header information - headers already sent by (output started at
but i managed fixing this using the init action.

The second problem was that no zip was downloaded.

My question is if anyone here have worked with ZipArchive in WP that would be able to show some samplecode. Or have any tips that may work.

Thanks.

7
  • Where and how is this code run? Commented Nov 23, 2021 at 10:57
  • @JacobPeattie In a plugin that i'm building. The plugin overwrites the woocommerce cart.php and that's where this code should run.
    – fredriktv
    Commented Nov 23, 2021 at 11:02
  • It doesn’t really make sense for cart.php to be a zip download like this. When are users supposed to be able to download these files? Commented Nov 23, 2021 at 11:32
  • @JacobPeattie I totally agree but this is a budget project and WooCommerce has the functionality and fields required for the project. So this was a good solution instead of developing all the product and cart functionality. awesomescreenshot.com/video/…
    – fredriktv
    Commented Nov 23, 2021 at 12:06
  • @JacobPeattie also ZipArchive doesn't work no matter if it's a cart page or any page in WordPress.
    – fredriktv
    Commented Nov 23, 2021 at 12:08

1 Answer 1

0

I successfully created zip file in root folder of WordPress using following code:

$files = array(__DIR__.'/test.jpg', __DIR__.'/screenshot.png');
$zipname = 'images.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE) or die(' cant open ');
foreach ($files as $file) {
 if( $zip->addFile($file)){
    echo "<br>$file Added To Zip Sucessfully";
 }else {
    echo "<br>Can not add $file file";
 }

}
$zip->close();


if(file_exists($zipname)){
    echo "<a href='$zipname' download> Download $zipname</a> ";
}else{
    echo "$zipname not Exists!";
}

I give a full path of images using __DIR__ and test each step by printing messages. you can provide a download link if it is not automatically downloaded. I hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.