Example code:
public function downLoad($dataUrl,$saveName) { $datalist = [ ROOT_PATH.'/public/introduce/', ROOT_PATH.'/public/upfile/' ]; // print_r($datalist);die; $filename = ROOT_PATH.'\public\/'.$saveName.'.zip'; if(file_exists($filename)){ unlink($filename); } $zip = new \ZipArchive(); if ($zip->open($filename,\ZipArchive::CREATE)!== true){ exit('Cannot open the file, or the file creation failed'); } foreach ($dataUrl as $index => $item) { if (DIRECTORY_SEPARATOR=='\\'){ $item = str_replace('/',DIRECTORY_SEPARATOR,$item); $filename = str_replace('/',DIRECTORY_SEPARATOR,$filename); } // var_dump($item); // var_dump(file_exists($item));die; if (file_exists($item)){ $zip->addFile($item,basename($item)); } } $zip->close(); if(!file_exists($filename)){ exit("File cannot be found"); //Even if created, it may still fail } header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.basename($filename)); header('Content-Length: ' . filesize($filename)); @readfile($filename); @unlink ( $filename ); }
Note: All paths inside use absolute paths, otherwise the file will not be found.
Additional operations:
Unzip the zip file
public function unzip_file($file, $dir){ // Instantiate the object $zip = new ZipArchive() ; //Open the zip document, if it fails to open, return the prompt message if ($zip->open($file) !== TRUE) { die ("Could not open archive"); } //Decompress the compressed file to the specified directory $zip->extractTo($dir); //Close the zip document $zip->close(); }
Get the directory of decompressed files
public function loopFun($dir) { $handle = opendir($dir."."); //Define an array to store file names $array_file = array(); while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $array_file[] = $dir.'/'.$file; //Output file name } } closedir($handle); return $array_file; //print_r($array_file); }
You can give me a thank you for your learning and support in the local test.