PHP ZipArchive is an extension class that comes with PHP, which can easily compress and decompress ZIP files. Before using it, first make sure that the PHP ZIP extension is turned on.
- /* Description: Function to compress multiple files into one zip file
- * @param $files array type
- * @param destination path of the target file
- * @param $overwrite whether it is Overwrite the same file as the destination file
- */
- function create_zip($files = array(),$destination = '',$overwrite = false){
- //If the zip file already exists and is set to not overwrite, return false
- if(file_exists($destination) && !$overwrite) { return false; }
- $valid_files = array();
- //Get the real and valid file name
- if(is_array($files)) {
- foreach($ files as $file) {
- if(file_exists($file)) {
- $valid_files[] = $file;
- }
- }
- }
- //If there are real and valid files
- if(count($valid_files)) {
- $zip = new ZipArchive();
- //Open the file. If the file already exists, overwrite it, if not, create it.
- if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE ) !== true) { return false; }
- //Add files to the compressed file
- foreach($valid_files as $file) {
- $zip->addFile($file,$file);
- }
- // Close the file
- $zip->close();
- //Check whether the file exists
- return file_exists($destination);
- }else{
- return false;
- }
- }
-
-
- $files = array('tg. php');
-
- create_zip($files,'tg.zip', true);
-
- ?>
Copy code
|