Heim  >  Artikel  >  Backend-Entwicklung  >  php 压缩文件为zip格式的函数代码

php 压缩文件为zip格式的函数代码

WBOY
WBOYOriginal
2016-07-25 08:59:22919Durchsuche
  1. /* @creates a compressed zip file 将多个文件压缩成一个zip文件的函数
  2. * @$files 数组类型 实例array("1.jpg","2.jpg");
  3. * @destination 目标文件的路径 如"c:/androidyue.zip"
  4. * @$overwrite 是否为覆盖与目标文件相同的文件
  5. * @site http://bbs.it-home.org
  6. */
  7. function create_zip($files = array(),$destination = '',$overwrite = false) {
  8. //if the zip file already exists and overwrite is false, return false
  9. //如果zip文件已经存在并且设置为不重写返回false
  10. if(file_exists($destination) && !$overwrite) { return false; }
  11. //vars
  12. $valid_files = array();
  13. //if files were passed in...
  14. //获取到真实有效的文件名
  15. if(is_array($files)) {
  16. //cycle through each file
  17. foreach($files as $file) {
  18. //make sure the file exists
  19. if(file_exists($file)) {
  20. $valid_files[] = $file;
  21. }
  22. }
  23. }
  24. //if we have good files...
  25. //如果存在真实有效的文件
  26. if(count($valid_files)) {
  27. //create the archive
  28. $zip = new ZipArchive();
  29. //打开文件 如果文件已经存在则覆盖,如果没有则创建
  30. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  31. return false;
  32. }
  33. //add the files
  34. //向压缩文件中添加文件
  35. foreach($valid_files as $file) {
  36. $zip->addFile($file,$file);
  37. }
  38. //debug
  39. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  40. //close the zip -- done!
  41. //关闭文件
  42. $zip->close();
  43. //check to make sure the file exists
  44. //检测文件是否存在
  45. return file_exists($destination);
  46. }else{
  47. //如果没有真实有效的文件返回false
  48. return false;
  49. }
  50. }
  51. /****
  52. //测试函数
  53. $files=array('temp.php','test.php');
  54. create_zip($files, 'myzipfile.zip', true);
  55. ****/
  56. ?>
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn