Created
April 9, 2018 11:39
-
-
Save teknikqa/30d6bbcd9ee6aa2c7d4686f142157108 to your computer and use it in GitHub Desktop.
Compress files into a single zip file
This file contains hidden or 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 | |
| /** | |
| * @file | |
| * Creates a compressed zip file. | |
| * | |
| * @author Original Author: David Walsh | |
| * @author Modified by: Nick Mathew | |
| * @link https://davidwalsh.name/create-zip-php | |
| */ | |
| /** | |
| * Compress files into a single zip file. | |
| * | |
| * @param string $files | |
| * Array of location of files that need to be zipped. | |
| * @param string $destination | |
| * (Optional) Destination path to save the zip file. | |
| * @param int $overwrite | |
| * (Optional) Overwrite the file if it already exists. Defaults to false. | |
| * | |
| * @return bool | |
| * Returns true if successful. | |
| */ | |
| function createZip($files = array(), $destination = '', $overwrite = FALSE) { | |
| // If the zip file already exists and overwrite is false, return false. | |
| if (file_exists($destination) && !$overwrite) { | |
| return FALSE; | |
| } | |
| $valid_files = array(); | |
| if (is_array($files)) { | |
| // Cycle through each file and make sure that each file exists. | |
| foreach ($files as $file) { | |
| if (file_exists($file)) { | |
| $valid_files[] = $file; | |
| } | |
| } | |
| } | |
| if (count($valid_files)) { | |
| $zip = new ZipArchive(); | |
| if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== TRUE) { | |
| return FALSE; | |
| } | |
| foreach ($valid_files as $file) { | |
| // Remove directory structure. | |
| $new_filename = substr($file, strrpos($file, '/') + 1); | |
| $zip->addFile($file, $new_filename); | |
| } | |
| $zip->close(); | |
| // Check to make sure the file exists. | |
| return file_exists($destination); | |
| } | |
| else { | |
| return FALSE; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment