PHP

PHP 압축파일 업로드해서 압축풀기

생활개발 2024. 12. 19. 15:50
728x90

고객사에서 원래 PDF파일을 올려서 보고있었는데

갑자기 ebook처럼 만든다고 index.html이랑 css js가 들어있는 압축파일을 업로드 하고싶다고 하셧다..

 

뭐 어떡해~~ 시키면 해야지

 

우선 PDF만 업로드 할 수 있던 로직을 ZIP만 업로드 할 수 있도록 변경!

전)

//파일 업로드 되어있는지 확인
if($_FILES['uploadFile']['name'] != null && $_FILES['uploadFile']['name'] != "")
{
    for( $i=0 ; $i < count($_FILES['uploadFile']['name']); $i++ ) {    
        $uploadFile = time().$_FILES['uploadFile']['name'][$i]; //파일명 같을때 덮어쓰기 방지
        $fileType = $_FILES['uploadFile']['type'][$i]; //파일 타입 추출

	//파일 타입 체크
        if($fileType !== "application/pdf")
        {
            ?>
            {
            "isSuc":"fail",
            "msg":"PDF 파일만 가능합니다."
            }
            <?php
            exit;
        }
}

후)

//파일 업로드 되어있는지 확인
if($_FILES['uploadFile']['name'] != null && $_FILES['uploadFile']['name'] != "")
{
    for( $i=0 ; $i < count($_FILES['uploadFile']['name']); $i++ ) {    
        $uploadFile = time().$_FILES['uploadFile']['name'][$i]; //파일명 같을때 덮어쓰기 방지
        $fileType = $_FILES['uploadFile']['type'][$i]; //파일 타입 추출

	//파일 타입 체크
        if($fileType !== "application/x-zip-compressed")
        {
            ?>
            {
            "isSuc":"fail",
            "msg":"ZIP 파일만 가능합니다."
            }
            <?php
            exit;
        }
}

여기는 크게 수정한거 없고 파일 타입 체크하는부분만 바꿧다

근데 한번씩 근데 난 이미지 파일을 올렷는데 $_FILES['upliadFile']['type'] 이게 없던 경우가 있던데

더좋은 방법 아시는분 있으면 댓글 부탁드립니다!

 

이제 파일 업로드해서 압축 푸는부분!

if(move_uploaded_file($_FILES['uploadFile']['tmp_name'][$i], "$uploadBase/$name_pdf_kor")){
    $zip = new ZipArchive;
    $zipfile = "$uploadBase/$uploadFile";

    // pathinfo를 사용하여 확장자를 제거한 파일 이름 추출
    $fileInfo = pathinfo($uploadFile);
    $dirName = $fileInfo['filename'];  //ex)aaa.zip -> aaa

    // 압축 파일을 열고, 압축을 풀기 위한 디렉토리 생성
    if($zip->open($zipfile) !== false){
        // 디렉토리 생성 (존재하지 않으면 생성)
        $dirPath = "$uploadBase/$dirName";
        if (!file_exists($dirPath)) {
            mkdir($dirPath, 0777, true); // 폴더 생성
        }

        // ZIP 내의 모든 파일을 지정된 폴더로 추출
        for($i = 0; $i < $zip->numFiles; $i++){
            $filename = $zip->getNameIndex($i);
            // 압축 파일 내의 파일을 지정된 디렉토리로 복사
            copy("zip://$zipfile#$filename", "$dirPath/" . basename($filename));
        }
        $zip->close();
    }
}

파일 업로드가 성공하면 압축파일의 zip를 뺀 파일명으로 디렉토리를 만들고

거기안에다 압축파일에 있는 파일들을 하나씩 넣어줍니다

 

작성하고 파일 업로드 해봤는데!

문제가 생겼어요.

이렇게 하니까 압축파일에 있는 폴더를 구분 안하고 그냥 $dirName 여기다가 파일들을 다 때려넣어 버려요.

 

디렉토리 구분하면서 파일업로드하고 풀어지도록 코드 수정

if(move_uploaded_file($_FILES['uploadFile']['tmp_name'][$i], "$uploadBase/$name_pdf_kor")){
    $zip = new ZipArchive;
    $zipfile = "$uploadBase/$uploadFile";

    // pathinfo를 사용하여 확장자를 제거한 파일 이름 추출
    $fileInfo = pathinfo($uploadFile);
    $dirName = $fileInfo['filename'];  //ex) aaa.zip -> aaa

    // 압축 파일을 열고, 압축을 풀기 위한 디렉토리 생성
    if($zip->open($zipfile) !== false){
        // 디렉토리 생성 (존재하지 않으면 생성)
        $dirPath = "$uploadBase/$dirName";
        if (!file_exists($dirPath)) {
            mkdir($dirPath, 0777, true); // 폴더 생성
        }

        // ZIP 내의 모든 파일을 지정된 폴더로 추출
        for($i = 0; $i < $zip->numFiles; $i++){
            $filename = $zip->getNameIndex($i);

            // 폴더 구조 유지하여 파일을 복사
            $filePath = "$dirPath/" . $filename;

            // 디렉토리인 경우 폴더를 생성
            if (substr($filename, -1) === '/') {
                // 디렉토리라면 해당 디렉토리를 생성
                if (!file_exists($filePath)) {
                    mkdir($filePath, 0777, true);
                }
            } else {
                // 파일인 경우 파일을 압축 해제 후 복사
                copy("zip://$zipfile#$filename", $filePath);
            }
        }
        $zip->close();
    }
}

 

이렇게하면 디렉토리별로 구분되서 파일 풀어지도록 끝~!

728x90