Online Snippets Library

Download Files from URL and Create zip

We will use ZipArchive() to create zip.ZIP class of PHP provides all the functionality that we need.

Example

<?php
$files = array(
    'http://www.tutsway.com/images/logo1.png',
    'http://img.youtube.com/vi/uGCnv3dv4gI/mqdefault.jpg'
);
$zip = new ZipArchive();
$zipname = 'images.zip';   // Zip file name.
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach($files as $file){
$urlStatus = get_headers($file, 1);  // Check image response
if ((strpos($urlStatus[0],'200 OK') !== false)){ 
$download_file = file_get_contents($file);
$zip->addFromString(basename($file),$download_file);
}
}
$zip->close();
header('Content-disposition: attachment; filename="'.$zipname.'"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
?>