본문 바로가기

php/코드이그나이터(CI3)

php 서버내의 폴더, 파일 압축

반응형
function dirZip($resource,$dir) 
{ 
    if(filetype($dir) === 'dir') {
      clearstatcache(); 

      if($fp = @opendir($dir)) { 
        while(false !== ($ftmp = readdir($fp))){ 
          if(($ftmp !== ".") && ($ftmp !== "..") && ($ftmp !== ""))
          { 
            if(filetype($dir.'/'.$ftmp) === 'dir') { 
              clearstatcache();   

              // 디렉토리이면 생성하기 
              $resource->addEmptyDir($dir.'/'.$ftmp); 
              set_time_limit(0);   

              $this->dirZip($resource,$dir.'/'.$ftmp); 
            } else { 

              // 파일이면 파일 압축하기 
              $resource->addFile($dir.'/'.$ftmp); 
            } 
          } 
        } 
      } 
      if(is_resource($fp)){ 
        closedir($fp);
      } 
    } else { 
      // 파일이면 파일 압축하기 
      $resource->addFile($dir); 
    } 
 }

3년전에 사용하던 압축 코드인데 다른 좋은 방법이 있겠지...만

그냥 간단하게 사용할수있어서 옮겨봤다.

 

사용법

// 압축할 디렉토리 
$dir = $this->config->item('batch_dir'); 
// 압축파일 이름(저장될 압축파일의 경로+이름)
$zipfile = $this->config->item('batch_dir')."zipfile.zip"; 
$zip = new ZipArchive; 
$res = $zip->open($zipfile, ZipArchive::CREATE); 

if ($res === TRUE) {        
    $this->dirZip($zip,$dir); 
    $zip->close();
    // zip파일 생성 부분 끝 

    //다운로드 부분 시작
    ob_start();
    ob_end_clean();
    $dn_zip_filesize = filesize($zipfile);
    header("Pragma: public");
    header("Expires: 0");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename={$zipfile}");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: {$dn_zip_filesize}");

    ob_clean();
    flush();
    readfile($zipfile);
} else { 
  echo "에러 코드: ".$res; 
}

함수명(zip파일,경로) 식으로 사용하면 되며

필수적으로 php의 zip 라이브러리가 필요하다

'php > 코드이그나이터(CI3)' 카테고리의 다른 글

파일다운로드  (0) 2024.05.12
파일업로드  (0) 2024.05.12
php exec 실행안될때 확인  (0) 2024.05.12
코드이그나이터3, 세션생성오류  (0) 2024.04.18
php sftp로 폴더 업로드  (2) 2024.04.18