header() 函數向客戶端發送原始的 HTTP 報頭,認識到一點很重要,即必須在任何實際的輸出被發送之前調用 header() 函數(在 PHP 4 以及更高的版本中,您可以使用輸出緩存來解決此問題):
- <html>
- <?php
- // 結果出錯
- // 在調用 header() 之前已存在輸出
- header('Location: http://www.49028c.com/');
- ?>
語法:
header(string,replace,http_response_code)參數 描述
string 必需,規定要發送的報頭字符串。
replace 可選,指示該報頭是否替換之前的報頭,或添加第二個報頭。
默認是 true(替換),false(允許相同類型的多個報頭).
http_response_code 可選,把 HTTP 響應代碼強制為指定的值(PHP 4 以及更高版本可用)
提示和注釋
注釋:從 PHP 4.4 之后,該函數防止一次發送多個報頭,這是對頭部注入攻擊的保護措施.
例子1:
- <?php
- // Date in the past
- header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
- header("Cache-Control: no-cache");
- header("Pragma: no-cache");
- ?>
- <html>
- <body>
注釋:用戶可能會設置一些選項來更改瀏覽器的默認緩存設置,通過發送上面的報頭,您可以覆蓋任何這些設置,強制瀏覽器不進行緩存!
例子2
提示用戶保存一個生成的 PDF 文件(Content-Disposition 報頭用于提供一個推薦的文件名,并強制瀏覽器顯示保存對話框):
- <?php
- header("Content-type:application/pdf");
- // 文件將被稱為 downloaded.pdf
- header("Content-Disposition:attachment;filename='downloaded.pdf'");
- // PDF 源在 original.pdf 中
- readfile("original.pdf");
- ?>
- <html>
- <body>
- ...
- ...
- <?php
- // 結果出錯
- // 在調用 header() 之前已存在輸出
- header('location: http://www.49028c.com/');
- ?>
語法:header(string,replace,http_response_code)
該函數防止一次發送多個報頭:
- <?php
- // date in the past
- header("expires: mon, 26 jul 1997 05:00:00 gmt");
- header("cache-control: no-cache");
- header("pragma: no-cache");
- ?>
提示用戶保存一個生成的 pdf 文件(content-disposition 報頭用于提供一個推薦的文件名,并強制瀏覽器顯示保存對話框):當時間超過指定時間就表示網頁內容已經失效。 其格式如下:
expires = “expires:” http-date
例 如: header(“expires: fri, 31 oct 2003 18:00:00 gmt”); 表示2003年10月31日星期五 18時。
header(“expires: wed, 30 jun 2004 09:00:00 gmt”); 表示2004年6月30日星期三 9時。
last-modified = “last-modified” “:” http-date
例如 header(“last-modified: wed, 01 jan 2003 12:00:00 gmt”); 上次修改時間2003年1月1日12時
cache control
no-cache 使得服務器的數據可以傳送到遠程的使用者,而不會被暫存(cache)起來,
no-store 是預防不良的版本或者是敏感的信息被保留下來。
must-revalidate 是指必須要再評估信息, 如果暫存 (cached) 的數據是無效的則讓服務器與使用者端聯機.
新聞熱點
疑難解答