Latest web development tutorials

PHP header () function

PHP HTTP Reference Manual Complete PHP HTTP Reference Manual

Definition and Usage

header () function to the client to send raw HTTP headers.

It is important to recognize that you must call the header () function before any actual output is sent (in PHP 4 and later versions, you can use output buffering to solve this problem):

<html>
<?php
// This results in an error.
// The output above is before the header() call
header('Location: http://www.example.com/');
?>

grammar

header(string,replace,http_response_code)

参数 描述
string 必需。规定要发送的报头字符串。
replace 可选。指示该报头是否替换之前的报头,或添加第二个报头。默认是 TRUE(替换)。FALSE(允许相同类型的多个报头)。
http_response_code 可选。把 HTTP 响应代码强制为指定的值。(PHP 4.3 以及更高版本可用)


Tips and Notes

NOTE: Starting after PHP 4.4, the function to prevent send multiple headers.This is a protection against head injection attacks.


Example 1

Disable page caching:

<?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>

...
...

Note: Users may set some options to change the default browser cache settings.By sending the headers above, you can override any of these settings, do not force the browser cache!


Example 2

Prompt the user to save a generated PDF file (Content-Disposition header is used to provide a recommended filename and force the browser to display the save dialog):

<?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>

...
...

NOTE: Microsoft IE 5.5 more than the existence of a mechanism to prevent the bug.By upgrading to Service Pack 2 or later versions, you can fix the bug.


PHP HTTP Reference Manual Complete PHP HTTP Reference Manual