header — 가공하지않은 HTTP 헤더를 송신한다.
설명 :
void header ( string $string [, bool $replace [, int $http_response_code ]]
)
header() 는 아무런 처리를 하지 않은(raw) HTTP 헤더를 송신하기위해 사용한다. HTTP 헤더에 대해 자세한 정보는 » HTTP/1.1 사양 을 참조할것.
header() 함수는 일반적인 HTML 태그 및 PHP 와는 상관없이 모든 실제 출력하기전에 콜되어야 한다. 자주 일어나는 에러로 include() 또는 require() 함수 다른 파일에 억세스하는 함수에 공백 , 빈줄이 들어가 header() 앞에서 출력이 발생하는 경우이다. 같은 에러로 단일 PHP/HTML 파일을 사용할때도 일어난다.
<?php
/* header() 를 콜하기전에 출력이 있기에 에러가 발생함
* */
header('Location: http://www.example.com/');
?>
파라미터 :
string
특수한 header 콜이 2종류있다. 먼저 문자열 "HTTP/" 로 시작하는 모든 헤더이다.(대문자. 소문자 구분없음) 이 헤더는 송신하는 HTTP 스테이터스코드를 표시하기 위해 사용된다. 예를 들어 존재하지 않는 파일에의 리퀘스트를 처리하기 위하여 PHP 스크립트를 사용하도록(ErrorDocument 디렉티브에 의해) Apache 를 설정할때 해당 스크립트가 알맞은 스테이터스 코드를 돌려주도록해야한다.
<?php
header("HTTP/1.0 404 Not
Found");
?>
2번째 특별한 헤더는 "Location:" 헤더이다. 이 헤더는 브라우저를 리다이렉트하며 , 브라우저에게
REDIRECT (302) 스테이터스코드를 돌려준다. (3xx 스테이터스 코드가 이미 송신되어 있지않는 경우만)
<?php
header("Location:
http://www.example.com/"); /* 브라우저를
리다이렉트*/
/* 리다이렉트후 , 이 밑으로는 실행
안됨.*/
exit;
?>
replace
<?php
header('WWW-Authenticate:
Negotiate');
header('WWW-Authenticate: NTLM', false);
?>
http_response_code
HTTP 리스폰스코드를 강제적으로
지정한다.
리턴 :
리턴하지 않음.
예 1 다운로드 다이얼로그PDF 파일을 생성한 경우 해당 파일을
다운로드할지를 확인하는 대화창을 표시하고 싶을것이다. 그런 경우 » Content-Disposition 헤더를 사용하여 파일명을
지정하면 브라우저에서 대화창을 표시할 수 있다.
<?php
// PDF 출력
header('Content-type: application/pdf');
// downloaded.pdf 라는 이름으로 저장
header('Content-Disposition: attachment;
filename="downloaded.pdf"');
// 원래 PDF 소스는 original.pdf
readfile('original.pdf');
?>
예2 캐쉬디렉티브
PHP 스크립트는 자주 동적 HTML 를 생성하기에 클라이언트 브라우저, 서버 및 클라이언트 브라우저 사이에서 프락시가 캐쉬를 행하거나 해서는 안된다. 많은 프락시와 클라이언트에서는 다음 코드에 의해 강제적으로 캐쉬를 무효화할 수 있다.
<?php
header("Cache-Control:
no-cache, must-revalidate");
// HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // 과거 날짜
?>
주의 : 위 헤더를 전부다 출력하지않더라도 페이지의 캐쉬가 일어나지
않는 경우가 있다. 디폴트 브라우저의 캐쉬동작을 사용자가 변경할 수 있는 방법은 몇가지가 있다. 위 헤더를 송신함으로 해서 스크립트의 출력이
캐쉬될 가능 성이 있는 설정을 덮어 쓰도록...
또한 session_cache_limiter() 및 설정
session.cache_limiter 를 이용하면 세션이 사용되었을때 캐쉬관계의 제대로된 헤더를 자동적으로 생성하도록 할 수
있다.
주의 : PHP 4 에서는 출력버퍼링을 사용하여 이 문제를 해결할 수 있다. 이 경우 브라우저에의 출력이
송신되기까지 서버에 전부 버퍼링되는 오버헤드가 있다. 출력 버퍼링은 ob_start() 와 ob_end_flush() 를 스크립트에서
콜하거나 php.ini , 서버 설정 파일의 설정 디렉티브
utput_buffering 을 설정하여 사용할 수 있다.
주의 : 실제로 header() 가 맨 처음에 콜되었는지와 상관없이 HTTP 스테이터스 헤더행은
클라이언트에게 항상 맨처음에 송신된다. HTTP 헤더가 이미 송신되어 있지않는한 header() 를 콜하여 스테이터스는 항상 덮어쓰게된다.
주의 : Microsoft Internet Explorer 4.01 에 버그가 있어서 이방법은 동작하지 않음
. 해결방법은 없다. 마찬가지로 Microsoft Internet Explorer 5.5 에서도 버그가 존재한다. 서비스팩 2 이후부터는
버그가 해결됨.
주의 : 세이프 모드가 유효한 경우는 WWW-Authenticate 헤더 (HTTP 인증에 사용) 을 설정했을때 스크립트의 uid가 realm 에 추가된다.
주의 : HTTP/1.1 에서는 스키마 , 호스트명 절대 패스를 포함한 절대 URI 가 » Location: 의 파라미터로서 필요하지만 상대 URI 를 받느 클라이언트도 있다. 일반적으로 상대 URI 로 절대 URI 를 생성하기위해서는 $_SERVER['HTTP_HOST'] , $_SERVER['PHP_SELF'] 및 dirname() 를 사용.
<?php
/* 현재 디렉토리의 다른 페이지로 리다이렉트 */
$host = $_SERVER['HTTP_HOST'];
$uri
= rtrim(dirname($_SERVER['PHP_SELF']),
'/\\');
$extra
= 'mypage.php';
header("Location:
http://$host$uri/$extra");
exit;
?>
주의 : session.use_trans_sid 가 유효라도 세션 ID 가 Location 헤더와 같이
넘겨지는 일은 없다. SID 정수를 사용하여 수동으로 넘겨줘야 한다.
JSON
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
header('Location: http://www.example.com/');
header("HTTP/1.0 404 Not Found");
header("Status: 404 Not Found");
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
header( "refresh:5;url=wherever.php" );
header('Content-Type: text/html; charset=utf-8');
header('Set-Cookie: track=978268624934537');
// We'll be outputting a PDF
header('Content-type: application/pdf');
header('Content-Type: image/png');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
<?php
// seconds, minutes, hours, days
$expires = 60*60*24*14;
header("Pragma: public");
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
?>
<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
?>
<?php
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file) ."; ");
header("filename=\"".$file."\"; ");
flush(); // this doesn't really matter.
?>
<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Content-type: text/javascript");
header("Content-Disposition: inline; filename=\"download.js\"");
header("Content-Length: ".filesize("my-file.js"));
} else {
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=\"download.js\"");
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Cache-Control: no-cache");
header("Pragma: no-cache");
}
include("my-file.js");
?>
워드
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; Filename=SaveAsWordDoc.doc");
header( "Content-Description: PHP4 Generated Data" );
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Pragma: public");
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
엑셀
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=회원리스트.xls");
header( "Content-Description: PHP4 Generated Data" );
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
header("Pragma: public");
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR"> : 내용중 문자셋 meta가 없을 경우 글자가 깨질수있음