<?php
//sample files in an array to be compressed
$files = array(
'images/img1.png',
'images/img2.png',
'images/img3.png',
'images/img4.png',
'images/img5.png'
);
//returns true if creation succeed and false if zip creation failed
$result = create_zip($files,'my-archive.zip');
//function that creates a compressed zip file
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//variable declaration
$valid_files = array();
//if files are valid
if(is_array($files)) {
//loops and check each file
foreach($files as $file) {
//check if file exists and store in array
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//check if there are valid files
if(count($valid_files)) {
//create the zip archive object
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add files to the object
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//close the zip after adding the files
$zip->close();
//check if the destination file exists
return file_exists($destination);
}
else {
return false;
}
}
?>
No comments:
Post a Comment