首页  >  文章  >  后端开发  >  PHP 片段即时压缩 zip 文件

PHP 片段即时压缩 zip 文件

WBOY
WBOY原创
2016-07-25 08:42:38785浏览

使用下面的 PHP 片段可以即时压缩 zip 文件

  1. function create_zip($files = array(),$destination = '',$overwrite = false) {
  2. //if the zip file already exists and overwrite is false, return false
  3. if(file_exists($destination) && !$overwrite) { return false; }
  4. //vars
  5. $valid_files = array();
  6. //if files were passed in...
  7. if(is_array($files)) {
  8. //cycle through each file
  9. foreach($files as $file) {
  10. //make sure the file exists
  11. if(file_exists($file)) {
  12. $valid_files[] = $file;
  13. }
  14. }
  15. }
  16. //if we have good files...
  17. if(count($valid_files)) {
  18. //create the archive
  19. $zip = new ZipArchive();
  20. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  21. return false;
  22. }
  23. //add the files
  24. foreach($valid_files as $file) {
  25. $zip->addFile($file,$file);
  26. }
  27. //debug
  28. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  29. //close the zip -- done!
  30. $zip->close();
  31. //check to make sure the file exists
  32. return file_exists($destination);
  33. }
  34. else
  35. {
  36. return false;
  37. }
  38. }
复制代码

用法:
  1. $files=array('file1.jpg', 'file2.jpg', 'file3.gif');
  2. create_zip($files, 'myzipfile.zip', true);
  3. ?>
复制代码

PHP, zip


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn