티스토리 뷰
웹서버에서 자료가 여러 개인 경우 사용자에게 개별 데이터를 하나하나 클릭해서 다운로드하게 하는 대신에 사용자가 일괄 다운로드를 요청하면 웹서버에서 동적으로 압축 파일을 생성해서 다운로드시키는 방법이다. 크게 두 가지 방법이 있는데, 하나는 서버 경로 상에 이미 존재하는 파일들을 압축 파일로 만들어서 내려보내는 방법이고, 다른 하나는 데이터베이스에 존재하는 것을 읽거나 기타 프로그램에 의해 동적으로 생성하는 내용을 압축 파일로 만들어서 내려보내는 방법이다.
■ 파일 동적 압축 다운로드
if (is_dir($folderName)) {
$archive_file_name = $folderName.'/downall.zip';
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
$dirfd = opendir($folderName);
if($dirfd) {
while(($readf = readdir($dirfd))) {
if (strpos($readf, ".jpg")!==false) {
$zip->addFile($folderName.'/'.$readf, iconv("UTF-8", "CP949",$readf));
}
}
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=downall.zip");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache");
header("Expires: 0");
readfile($archive_file_name);
@unlink($archive_file_name);
exit;
}
위의 코드는 $folderName로 지정한 폴더에서 확장자가 *. jpg 파일들을 downall.zip 압축 파일로 묶어서 압축 파일을 다운로드하고 생성했던 압축 파일은 삭제하는 과정을 보여준다. ZipArchive 클래스를 생성하여 지정한 압축 파일을 열고 addFile(파일 경로, 항목 이름)로 개별 파일을 추가한 다음에 close()로 압축 파일 생성을 완료한다.
■ 스트링 동적 압축 다운로드
$archive_file_name = '/tmp/downall.zip';
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
$result = sql_query("SELECT * FROM filestore WHERE fname LIKE '%.jpg'");
while (($row=sql_fetch_array($result)) && isset($row[fname])) {
$zip->addFromString(iconv("UTF-8", "CP949",$row[fname]), $row[fbody]);
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=downall.zip");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache");
header("Expires: 0");
readfile($archive_file_name);
@unlink($archive_file_name);
exit;
위의 코드는 데이터베이스에 저장되어 있는 파일 중에서 확장자가 *. jpg 파일들을 downall.zip 압축 파일로 묶어서 압축 파일을 다운로드하고 생성했던 압축 파일은 삭제하는 과정을 보여준다. ZipArchive 클래스를 생성하여 지정한 압축 파일을 열고 addFromString(항목 이름, 항목 내용)으로 개별 파일을 추가한 다음에 close()로 압축 파일 생성을 완료한다.
압축 파일을 추가할 때 파일 이름에 한글이 포함된 경우를 감안하여 항목 이름은 iconv("UTF-8", "CP949", 항목 이름)과 같은 방식으로 인코딩을 바꾸어 주고 있음에 주의한다. ZIP 파일이 UTF-8 인코딩을 지원하지 않기 때문이다.

'프로그래밍' 카테고리의 다른 글
| 윈도우 10에서 프로그램 비정상 종료시 덤프를 남기도록 설정하는 방법 (0) | 2025.08.18 |
|---|---|
| C# 라운드 박스 컨트롤 만들기 (0) | 2025.08.06 |
| C# PictureBox에서 이미지가 자동으로 돌아가는 문제 해결, Exif (0) | 2025.07.08 |
| C# 난독화시 악성코드로 오탐지되는 문제 해결 방법 (0) | 2025.07.08 |
| 파이썬 배열(Array) - 파이썬 배우기(Python) (0) | 2024.05.10 |