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。
完整的PHP HTTP參考手冊