Created
April 23, 2024 10:03
-
-
Save md-riaz/a4dceccf750831991b5d5d00dd8afa2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function create_zip(array $files, string $destination, bool $overwrite = false): bool | |
{ | |
// If the zip file already exists and overwrite is false, throw an exception | |
if (file_exists($destination) && !$overwrite) { | |
throw new Exception("Zip file already exists and overwrite is false."); | |
} | |
// Filter out any non-existing files | |
$valid_files = array_filter($files, "file_exists"); | |
// If we have valid files... | |
if (count($valid_files)) { | |
// Create the archive | |
$zip = new ZipArchive(); | |
if ($zip->open($destination, $overwrite ? ZipArchive::OVERWRITE : ZipArchive::CREATE) !== true) { | |
throw new Exception("Cannot open the zip archive."); | |
} | |
// Add the files | |
foreach ($valid_files as $file) { | |
$zip->addFile($file, basename($file)); | |
} | |
// Close the zip -- done! | |
$zip->close(); | |
// Check to make sure the file exists | |
return file_exists($destination); | |
} else { | |
throw new Exception("No valid files provided."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment