주요 해결 방법
1. 출력 버퍼링 사용
ob_start();
// 페이지 내용
ob_end_flush();
2. 헤더 설정 위치 조정
3. UTF-8 BOM 제거
sed -i '1s/^\xEF\xBB\xBF//' filename.php
출력 제어 함수 활용
function sendResponse($data) {
ob_start();
header('Content-Type: application/json');
echo json_encode($data);
ob_end_flush();
}
리다이렉션 처리
function safeRedirect($url) {
if (!headers_sent()) {
header('Location: ' . $url);
exit;
}
echo '<script>window.location.href="' . $url . '";</script>';
echo '<noscript><meta http-equiv="refresh" content="0;url=' . $url . '"></noscript>';
exit;
}
모범 사례
1. 파일 구조화
<?php
// 설정 및 초기화
require_once 'config.php';
session_start();
// 헤더 설정
header('Content-Type: text/html; charset=UTF-8');
// HTML 출력
?>
<!DOCTYPE html>
2. 클래스 기반 응답 처리
class Response {
public static function json($data) {
if (!headers_sent()) {
header('Content-Type: application/json');
}
echo json_encode($data);
exit;
}
}
실제 구현 예시
<?php
ob_start();
session_start();
// 설정
header('Content-Type: text/html; charset=UTF-8');
// 페이지 로직
$data = ['status' => 'success'];
// JSON 응답
header('Content-Type: application/json');
echo json_encode($data);
ob_end_flush();