php 文件打包zip格式的实现方法

前端之家收集整理的这篇文章主要介绍了php 文件打包zip格式的实现方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:
  1. <?PHP
  2. /**
  3. * 打包zip格式文件
  4. *
  5. * @param
  6. * @arrange (512.笔记) jb51.cc
  7. **/
  8. function create_zip($files = array(),$destination = '',$overwrite = false) {
  9. //if the zip file already exists and overwrite is false,return false
  10. if(file_exists($destination) && !$overwrite) { return false; }
  11. //vars
  12. $valid_files = array();
  13. //if files were passed in...
  14. if(is_array($files)) {
  15. //cycle through each file
  16. foreach($files as $file) {
  17. //make sure the file exists
  18. if(file_exists($file)) {
  19. $valid_files[] = $file;
  20. }
  21. }
  22. }
  23. //if we have good files...
  24. if(count($valid_files)) {
  25. //create the archive
  26. $zip = new ZipArchive();
  27. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  28. return false;
  29. }
  30. //add the files
  31. foreach($valid_files as $file) {
  32. $zip->addFile($file,$file);
  33. }
  34. //debug
  35. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  36. //close the zip -- done!
  37. $zip->close();
  38. //check to make sure the file exists
  39. return file_exists($destination);
  40. }
  41. else
  42. {
  43. return false;
  44. }
  45. }
  46. /***** Example Usage ***/
  47. $files=array('file1.jpg','file2.jpg','file3.gif');
  48. create_zip($files,'myzipfile.zip',true);
  49. /*** 来自:编程之家 jb51.cc(jb51.cc) ***/
  50. ?>

猜你在找的PHP相关文章