PHP header() 函數

定義和用法
header() 函數向客戶端發送原始的 HTTP 報頭。
認識到一點很重要,即必須在任何實際的輸出被發送之前調用 header() 函數(在 PHP 4 以及更高的版本中,您可以使用輸出緩衝來解決這個問題):
<html>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>
語法
header(string,replace,http_response_code)
參數 | 描述 |
---|---|
string | 必需。規定要發送的報頭字串。 |
replace | 可選。指示該報頭是否替換之前的報頭,或添加第二個報頭。默認是 TRUE(替換)。FALSE(允許相同類型的多個報頭)。 |
http_response_code | 可選。把 HTTP 回應代碼強制為指定的值。(PHP 4.3 以及更高版本可用) |
提示和注釋
注釋:從 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>
...
...
// 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");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
<html>
<body>
...
...
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
<html>
<body>
...
...
注釋:微軟 IE 5.5 存在一個阻止以上機制的 bug。通過升級為 Service Pack 2 或更高的版本,可以解決該 bug。
