Wordpress can't use ZipArchive

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.

Topic ziparchive headers php plugin-development Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.