mixed ZipArchive::open ( string $filename [, int $flags ] )
(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

zip 압축 클레스로 할 수 있는 일은 읽고, 압축하고, 해제하고, 수정할 수 있는 거의 모든 작업을 할 수 있습니다. $flags는 다음 상수를 사용할 수 있습니다.

상 수 설 명
ZIPARCHIVE::OVERWRITE
ZIPARCHIVE::CREATE
ZIPARCHIVE::CHECKCONS

압축파일 오픈 작업이 성공하면 true를, 실패하면 다음 표의 상수를 반환합니다.

상 수 설 명
ZIPARCHIVE::ER_EXISTS 값: 10
ZIPARCHIVE::ER_INCONS 값: 21
ZIPARCHIVE::ER_INVAL 값: 18
ZIPARCHIVE::ER_MEMORY 값: 14
ZIPARCHIVE::ER_NOENT 값: 9
ZIPARCHIVE::ER_NOZIP 값: 19
ZIPARCHIVE::ER_OPEN 값: 11
ZIPARCHIVE::ER_READ 값: 5
ZIPARCHIVE::ER_SEEK 값: 4


Zip 압축 파일 해제

작성방법은 압축파일을 "오픈"하고, 원하는 위치에 압축 "해제"하고, "닫기" 순으로 작성합니다.

<?php
 $zip = new ZipArchive;
 // 압축파일이 있는 위치를 지정합니다.
 $res = $zip->open('./zzz/phpzipfile.zip');
 if (($res === TRUE) && (file_exists('./mail') === TRUE)) {
    echo '압축파일 오픈에 성공하였습니다.';

    // 다음 디렉토리 위치에 압축파일을 해제하도록 하겠습니다.
    $zip->extractTo('./mail');

    // 모든 작업이 완료되었으면 닫습니다.
    $zip->close();
    echo "ok";
 } else {
    // 압축파일 오픈에 실패하면 에러코드를 표시합니다.
    if(ZIPARCHIVE::ER_NOZIP === $res) {
         echo '압축파일을 찾을 수 없습니다.';
    }
 }
 ?>

다음은 디렉토리에 압축파일을 부분적으로 해제하도록 하겠습니다.

<?php
 $zip = new ZipArchive;
 // 압축파일이 있는 위치를 지정합니다.
 $res = $zip->open('./zzz/phpzipfile.zip');
 if (($res === TRUE) && (file_exists('./mail') === TRUE)) {
    echo '압축파일 오픈에 성공하였습니다.';

    // 다음 디렉토리 위치에 압축파일을 부분적으로 해제하도록 하겠습니다.
    // 전체가 아닌 부분적으로 해제할 파일을 $file_array배열에 작성합니다.
    $file_array = array("test.php","test.txt", "PHPgoldfile.php");
    $zip->extractTo('./mail',$file_array);

    // 모든 작업이 완료되었으면 닫습니다.
    $zip->close();
    echo "ok";
 } else {
    // 압축파일 오픈에 실패하면 에러코드를 표시합니다.
    if(ZIPARCHIVE::ER_NOZIP === $res) {
         echo '압축파일을 찾을 수 없습니다.';
    }
 }
 ?>


Zip 압축 파일내 Entry 얻기

압축 파일내 Entry 를 가져 오겠습니다. 가져오는 순서는 같습니다. 열기, 읽기, 닫기 순으로 작성합니다.

<?php 
 $zip = new ZipArchive; 
 if ($err = $zip->open('phpzipfile.zip')){ 
     for($i = 0; $i < $zip->numFiles; $i++) {
          // 디렉토리는 끝에 /가 붙습니다.
          echo 'filename: ' . $i. $zip->getNameIndex($i) . '<br />'; 
     }
     $zip->close();
 } else { 
     echo '압축파일을 읽을 수 없습니다.'; 
 } 

 /*
 결과:
 filename: 0 phpzipfile/
 filename: 1 phpzipfile/PHPgoldfile.php
 filename: 2 phpzipfile/READ-ME.html
 filename: 3 ./mail/
 flename: 4 ./news/
 flename: 5 test.txt
 flename: 6 PHPgoldfile.php
 flename: 7 russian_letters/
 flename: 8 1111entryname.txt
 flename: 9 dir/PHPgoldfile.php
 flename: 10 test.php
 */
 ?>


Zip 압축 파일내 파일삭제

이제 부분적으로 압축 파일내 파일을 삭제해 보겠습니다.

<?php 
 $zip = new ZipArchive; 
 if ($err = $zip->open('phpzipfile.zip')){ 
    // 파일내 test.php파일을 삭제하겠습니다.
    // 인덱스 번호로 파일을 삭제할 수도 있습니다. Index 10은 test.php파일입니다.
    // $zip->deleteIndex(10);
    if($zip->deleteName('test.php')){
         echo "ok!";
    }
    // 엔트리 얻기
    for($i = 0; $i < $zip->numFiles; $i++) {
          echo 'filename: ' . $i . $zip->getNameIndex($i) . '<br />'; 
     }
     $zip->close();
 } else { 
     echo '압축파일을 읽을 수 없습니다.'; 
 } 

 /*
 결과:
 filename: 0 phpzipfile/
 filename: 1 phpzipfile/PHPgoldfile.php
 filename: 2 phpzipfile/READ-ME.html
 filename: 3 ./mail/
 flename: 4 ./news/
 flename: 5 test.txt
 flename: 6 PHPgoldfile.php
 flename: 7 russian_letters/
 flename: 8 1111entryname.txt
 flename: 9 dir/PHPgoldfile.php
 */
 ?>


Zip 압축 파일 수정

압축 파일에 새로운 파일을 추가하거나 디렉토리를 만들 수 있습니다.

<?php
 if($fp = fopen('test.php','r')){
      $string = fread($fp,filesize('test.php'));
      if(is_resource($fp)){
           fclose($fp);
      }
 }

 $zip = new ZipArchive;
 $res = $zip->open('phpzipfile.zip');
 if ($res === TRUE) {
      // dir/pear.php에 $string을 작성합니다.
      // dir/pear.php파일이 없으면 디렉토리와 파일을 새로 만듭니다.
      $zip->addFromString('dir/pear.php', $string);

      // 압축파일을 오픈하여 test.php파일의 내용을 copyfile.txt 파일에 복사합니다.
      // copyfile.txt 파일이 없으면 새로 만듭니다.
      $zip->addFile('test.php', 'copyfile.txt');

      // test.php파일을 압축파일에 추가합니다.
      $zip->addFile('test.php');

      // 압축파일내에 "user/mkdir"디렉토리를 만듭니다.
      $zip->addEmptyDir("user/mkdir");

      // PHPgoldfile.php파일을 newname.txt파일로 이름을 변경합니다.
      $zip->renameName('PHPgoldfile.php','newname.txt');

      // 닫기
      $zip->close();
      echo 'ok';
 } else {
    echo 'failed: '.$res;
 }
 ?>

다음은 압축 파일내 특정 이미지 파일을 png 로 출력해 보겠습니다.

<?php
 $zip = new ZipArchive;
 $res = $zip->open('phpzipfile.zip');
 if ($res === TRUE) {
      $image = $zip->getFromName('test.bmp');
      $img = imagecreatefromstring($image);
      imagepng($img, 'test.png');

      $zip->close();
      echo 'ok';
 } else {
    echo 'failed: '.$res;
 }
 ?>


Zip 압축 파일 만들기

이 기능으로 특정 폴더를 압축해 보겠습니다. 압축하려면 ZipArchive::CREATE상수를 정의해야 하며, 이미 압축파일이 존재한다면 ZipArchive::OVERWRITE로 파일을 덮어 쓰게 합니다.

<?php
 $zip = new ZipArchive;
 $res = $zip->open('tempfile.zip', ZipArchive::CREATE);
 if ($res === TRUE) { 
      $zip->addFile('test.php');
      $zip->addFile('globtmpfile.php');
      $zip->close();
 } else {
      echo "에러 코드: ".$res;
 }
 ?>


Zip 압축 파일에 코멘트 달기

mixed ZipArchive::setCommentName ( string $name , string $comment )
(PHP 5 >= 5.2.0, PECL zip >= 1.4.0)

zip 압축 파일내 대상 파일에 설명을 붙일 수 있는 기능을 제공하는데, 다음 그림의 "설명" 부분을 보면 알 수 있듯이 필요하다면 코멘트를 남길 수 있습니다.


<?php
 $zip = new ZipArchive;
 $res = $zip->open('php.zip');
 if ($res === TRUE) {
      $zip->setCommentName('test.txt', '코멘트를 남깁니다.');
      $zip->close();
      echo 'ok';
 } else {
      echo 'error';
 } 
 ?>

이제 파일에 정상적으로 코멘트가 기록되었는지 확인해 보겠습니다.

<?php
 $zip = new ZipArchive;
 $res = $zip->open('php.zip');
 if ($res === TRUE) {
      // Index를 알고 있다면 ZipArchive::getCommentIndex를 사용해도 됩니다.
      var_dump($zip->getCommentName('test.txt')); // 결과: string(18) "코멘트를 남깁니다."
 } else {
      echo '에러 코드:' . $res;
 }
 ?> 

0 댓글