Skip to content

Instantly share code, notes, and snippets.

@md-riaz
Created April 23, 2024 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save md-riaz/a4dceccf750831991b5d5d00dd8afa2a to your computer and use it in GitHub Desktop.
Save md-riaz/a4dceccf750831991b5d5d00dd8afa2a to your computer and use it in GitHub Desktop.
<?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