PHP로 파일 다운로드 기능을 구현할 때 한글 파일명이 깨지는 문제는 매우 흔한 이슈입니다. 브라우저마다 다른 인코딩 방식을 사용하기 때문에 발생하는 문제로, 다음과 같은 해결책들을 사용할 수 있습니다.
<?php
$filename = "한글파일명.pdf";
$filepath = "/path/to/file/" . $filename;
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . urlencode($filename) . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
?>
<?php
$filename = "한글파일명.pdf";
$filepath = "/path/to/file/" . $filename;
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename));
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
?>
<?php
$filename = "한글파일명.pdf";
$filepath = "/path/to/file/" . $filename;
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Trident') !== false) {
// Internet Explorer
$encoded_filename = urlencode($filename);
} else {
// Chrome, Firefox, Safari 등
$encoded_filename = $filename;
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
?>
<?php
$filename = "한글파일명.pdf";
$filepath = "/path/to/file/" . $filename;
// UTF-8로 인코딩 확인 및 변환
if (!mb_check_encoding($filename, 'UTF-8')) {
$filename = mb_convert_encoding($filename, 'UTF-8', 'auto');
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
?>
<?php
function downloadFile($filepath, $filename = null) {
if (!file_exists($filepath)) {
die('파일이 존재하지 않습니다.');
}
if ($filename === null) {
$filename = basename($filepath);
}
// 출력 버퍼 정리
if (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
header('Content-Length: ' . filesize($filepath));
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($filepath);
exit;
}
// 사용 예시
downloadFile('/path/to/file.pdf', '한글파일명.pdf');
?>
<?php
$filename = "한글파일명.pdf";
$filepath = "/path/to/file/" . $filename;
$encoded_filename = '=?UTF-8?B?' . base64_encode($filename) . '?=';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
?>