php 將檔案壓縮為zip檔案

來源:互聯網
上載者:User
PHP ZipArchive 是PHP內建的擴充類,可以輕鬆實現ZIP檔案的壓縮和解壓,使用前首先要確保PHP ZIP 擴充已經開啟。
  1. /* 說明: 將多個檔案壓縮成一個zip檔案的函數
  2. * @param $files 數群組類型
  3. * @param destination 目標檔案的路徑
  4. * @param $overwrite 是否為覆蓋與目標檔案相同的檔案
  5. */
  6. function create_zip($files = array(),$destination = '',$overwrite = false){
  7. //如果zip檔案已經存在並且設定為不重寫返回false
  8. if(file_exists($destination) && !$overwrite) { return false; }
  9. $valid_files = array();
  10. //擷取到真實有效檔案名稱
  11. if(is_array($files)) {
  12. foreach($files as $file) {
  13. if(file_exists($file)) {
  14. $valid_files[] = $file;
  15. }
  16. }
  17. }
  18. //如果存在真實有效檔案
  19. if(count($valid_files)) {
  20. $zip = new ZipArchive();
  21. //開啟檔案 如果檔案已經存在則覆蓋,如果沒有則建立
  22. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; }
  23. //向壓縮檔中添加檔案
  24. foreach($valid_files as $file) {
  25. $zip->addFile($file,$file);
  26. }
  27. //關閉檔案
  28. $zip->close();
  29. //檢測檔案是否存在
  30. return file_exists($destination);
  31. }else{
  32. return false;
  33. }
  34. }
  35. $files = array('tg.php');
  36. create_zip($files,'tg.zip', true);
  37. ?>
複製代碼
檔案壓縮, php, zip
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.