PHP 片段即时压缩 zip 文件

WBOY
發布: 2016-07-25 08:42:38
原創
785 人瀏覽過

使用下面的 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


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!