[php] PHP에서 ZIP 파일 압축하기

PHP에서 파일을 ZIP으로 압축하는 것은 매우 유용한 기능입니다. 이 기능을 사용하면 여러 파일을 하나의 ZIP 파일로 묶어서 다운로드하거나 저장할 수 있습니다. 이 포스트에서는 PHP에서 ZIP 파일을 생성하는 방법에 대해 알아보겠습니다.

1. ZIP 클래스 사용하기

PHP에는 ZIP 파일을 생성하기 위한 내장 클래스가 있습니다. ZipArchive 클래스를 사용하여 파일을 ZIP으로 압축할 수 있습니다.

$zip = new ZipArchive();
$zip->open('compressed.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

$zip->addFile('file1.txt', 'file1.txt');
$zip->addFile('file2.txt', 'file2.txt');

$zip->close();

위의 코드 예제에서는 ZipArchive 클래스를 사용하여 compressed.zip이라는 새 ZIP 파일을 생성하고, file1.txtfile2.txt 파일을 압축 파일에 추가하는 방법을 보여줍니다.

2. 파일 추가 및 폴더 압축하기

또한, 여러 파일을 하나의 디렉토리로 압축할 수도 있습니다.

$zip = new ZipArchive();
$zip->open('compressed.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('path_to_directory/')
);

foreach ($files as $file) {
    if (!$file->isDir()) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen('path_to_directory/'));
        $zip->addFile($filePath, $relativePath);
    }
}

$zip->close();

위의 코드는 지정된 디렉토리의 모든 파일과 폴더를 compressed.zip이라는 파일로 압축하는 방법을 보여줍니다.

3. 다운로드 링크 생성

ZIP 파일을 생성한 후에는 생성된 ZIP 파일을 다운로드할 수 있는 링크를 제공해야 합니다.

$filePath = 'compressed.zip';

if (file_exists($filePath)) {
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="compressed.zip"');
    readfile($filePath);
    unlink($filePath); // 다운로드 후에 파일 삭제
}

위의 코드는 ZIP 파일 다운로드를 위한 링크를 생성하는 방법을 보여줍니다. 생성된 ZIP 파일은 다운로드한 후에 삭제됩니다.

이제 PHP에서 파일을 ZIP으로 압축하고, 생성된 ZIP 파일을 다운로드하는 방법을 알아보았습니다. 이를 통해 사용자가 여러 파일을 편리하게 다운로드할 수 있도록 할 수 있습니다.