PHP header()Functions


PHP HTTP 参考手册Complete PHP HTTP Reference Manual

Definition and Usage

The header() function sends a raw HTTP header to the client.

It is important to realize that the header() function must be called before any actual output is sent (in PHP 4 and higher, 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/');
?>

Syntax

header(string,replace,http_response_code)

Parameters Description
string Required. Specifies the header string to be sent.
replace Optional. Indicates whether the header should replace a previous header, or add a second header. Default is TRUE (replace). FALSE (allows multiple headers of the same type).
http_response_code Optional. Forces the HTTP response code to the specified value. (Available in PHP 4.3 and higher)


Tips and Notes

Note:As of PHP 4.4, this function prevents sending multiple headers at once. This is a protection against header 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 options that change the browser's default caching settings. By sending the above headers, you can override any of these settings and force the browser not to cache!


Example 2

Prompt the user to save a generated PDF file (the 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 has a bug that prevents the above mechanism. Upgrading to Service Pack 2 or higher can fix this bug.


PHP HTTP 参考手册Complete PHP HTTP Reference Manual Other Extensions