[PHP] PHP에서 파일을 압축 또는 해제하는 방법


Development note/PHP  2019. 11. 7. 09:00

안녕하세요. 명월입니다.


이 글은 PHP에서 파일을 압축 또는 해제하는 방법에 대한 설명입니다.


프로그램 상에서 여러가지 이유로 파일을 압축 또는 해제를 할 경우가 있습니다. 예전에 Java나 C#에서 파일을 압축 또는 해제에 대해 글을 쓴적이 있습니다.

링크 - [Java] Zip 압축하기

링크 - [Java] Zip 압축 해제하기

링크 - [C#] Zip 압축 코드 소스


PHP에서도 사용해 보겠습니다.

링크 - https://www.php.net/manual/en/book.zip.php

링크 - https://www.php.net/manual/en/zip.examples.php

링크 - https://www.php.net/manual/en/class.ziparchive.php

링크 - https://www.php.net/manual/en/ziparchive.extractto.php


예전에 사용했던 upload 소스를 이용했습니다.

링크 - [PHP] ajaxForm을 이용한 파일 업로드(프로그래스바로 파일 업로드 상태를 표시하는 방법)


<!DOCTYPE html>
<html>
<head>
  <title>title</title>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
<body>
  <form enctype="multipart/form-data">
    <input type="file" name="data">
    <input type="submit">
  </form>
  <br />
  <br />
  <div class="progress-label"></div>
  <div id="progressbar"></div>
  <br />
  <br />
  <label>file list</label>
  <div class="file-list"></div>
  
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <script>
    $(function() {
      var progressbar = $("#progressbar");
      var progressLabel = $(".progress-label");
      progressbar.progressbar({
        value: true,
        change: function() {
          progressLabel.text("Current Progress: " + progressbar.progressbar("value") + "%");
        },
        complete: function() {
          progressLabel.text("Complete!");
          $(".ui-dialog button").last().trigger("focus");
        }
      });
      $('form').ajaxForm({
        url: "upload.php",
        type: "POST",
        beforeSubmit: function(arr, $form, options) {
          progressbar.progressbar("value", 0);
        },
        uploadProgress: function(event, position, total, percentComplete) {
          progressbar.progressbar("value", percentComplete);
        },
        success: function(text, status, xhr, element) {
          progressbar.progressbar("value", 100);
          // 업로드가 완료되면 file-list에 압축 파일 안의 데이터 리스트를 표시한다.
          var list = JSON.parse(text);
          console.log(list);
          var html="";          
          for(i=0;i<list.length;i++){
            html += "index : " + i + "     name : " + list[i].name + "    size: " + list[i].size + "byte<br />";
          }
          $(".file-list").html(html);
        }
      });
    });
  </script>
</body>
</html>
<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 압축 클래스
    $zip = new ZipArchive();
    $filename = "d:\\file\\upload.zip";

    // 압축파일 열기
    if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
      exit("cannot open <$filename>\n");
    }
    
    // 압축 파일 추가하기
    $zip->addFile($_FILES["data"]["tmp_name"],$_FILES["data"]["name"]);
    // 클래스 닫기
    $zip->close();
    
    // 압축 파일 열기
    if ($zip->open($filename)!==TRUE) {
      exit("cannot open <$filename>\n");
    }
    $list = [];
    for ($i=0; $i<$zip->numFiles;$i++) {
      // 파일 리스트 담기
      array_push($list,$zip->statIndex($i));
    }
    //$zip->extractTo("d:\\file\\");
    $zip->close();
    // json 형식으로 응답
    echo json_encode($list);
  }

먼저 a.txt와 b.txt, c.txt 파일을 서버 측으로 전송합니다. update.php에서는 업로드받은 파일을 upload.zip의 압축 파일에 파일을 저장합니다.

참고로 같은 이름의 파일은 덮어쓰기를 합니다. 다시 압축파일을 열고 리스트를 받아서 json형태로 ajax를 응답합니다.

index.php에서는 json형태로 받은 값을 div.file-list에 표시합니다.


여기까지 PHP에서 파일을 압축 또는 해제하는 방법에 대한 설명이었습니다.


궁금한 점이나 잘못된 점이 있으면 댓글 부탁드립니다.