setcookie를 문서의 중간(정확하게 말하면 무엇인가 출력이 된후)에서 호출하면Warning: Cannot modify header information - headers already sent by 와 같은 에러가 나면서 저장되지 않는다. 이는 이미 헤더를 보냈으므로 수정할 수 없다 라는 뜻인데 이에 대한 해결책은 javascript로 하거나 페이지 전체의 출력을 ob_start와 ob_end_flush로 묶어 한번에 전송하는 방법밖에 없다.
function addCookie($name, $value, $expire, $path='/')
{
if (headers_sent()) {
$cookie = $name.'='.urlencode($value).';';
if ($expire) $cookie .= ' expires='.gmdate('D, d M Y H:i:s', $expire).' GMT';
echo '<script language="javascript">document.cookie="'.$cookie.'";</script>';
} else {
setcookie($name, $value, $expire, $path);
}
}
위 함수는 헤더가 이미 보내졌을때는 스크립트로 처리하고, 그외의 경우는 원래의 setcookie를 이용하는 방법이다. |
Posted on 2009/01/22 13:03
Filed Under Development/PHP