>  기사  >  백엔드 개발  >  PHP 片段即时压缩 zip 文件

PHP 片段即时压缩 zip 文件

WBOY
WBOY원래의
2016-07-25 08:42:38786검색

使用下面的 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으로 문의하세요.