Reputation:
I am trying to add functionality to my website where users can download multiple image files via a single .zip
folder. Currently I have this code executing but when i open the downloaded zip file it extracts another zip file my-archive (3) 2.zip.cpgz
and every time I try to open it, it extracts yet another zip file.
Here is my basic code using php native zip feature.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
$files = array($image1, $image2);
$zipname = 'file.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);
EDIT
I am trying hard to get the provided answer to work. I just tried the most recent edit and got this error
]
Upvotes: 1
Views: 9312
Reputation: 97
Hi guys above code worked perfectly. Images download worked only on live server (only if we use https or http). But it is not worked in local (if we use https or http).. If you use local follow this -> Only change below lines. For local use below img's $image1 = "C:/Users/User/Pictures/Saved Pictures/chandamama.jpg"; $image2 = "C:/Users/User/Pictures/Saved Pictures/beautifull.jpg"; Do not use below img's for local. $image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg"; $image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
Upvotes: 0
Reputation: 6726
You should download external files and then archive them.
$image1 = "http://cdn.screenrant.com/wp-content/uploads/Darth-Vader-voiced-by-Arnold-Schwarzenegger.jpg";
$image2 = "http://cdn.screenrant.com/wp-content/uploads/Star-Wars-Logo-Art.jpg";
$files = array($image1, $image2);
$tmpFile = tempnam('/tmp', '');
$zip = new ZipArchive;
$zip->open($tmpFile, ZipArchive::CREATE);
foreach ($files as $file) {
// download file
$fileContent = file_get_contents($file);
$zip->addFromString(basename($file), $fileContent);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=file.zip');
header('Content-Length: ' . filesize($tmpFile));
readfile($tmpFile);
unlink($tmpFile);
In example above I used file_get_contents
function, so please enable allow_url_fopen
or use curl to download the files.
Upvotes: 8