PHP header() Function
Definition and Usage
The header() function sends the original HTTP header to the client.
It is important to note that the header() function must be called before any actual output is sent (in PHP 4 and higher versions, you can use output buffering to solve this problem):
<html> <?php // Error occurred // Output already exists before calling header() header('Location: http://www.example.com/'); ?>
Syntax
header(string,replace,http_response_code)
Parameter | Description |
---|---|
string | Required. Specifies the header string to be sent. |
replace |
Optional. Indicates whether the header replaces the previous header or adds a second header. The default is true (replacement). false (allow multiple headers of the same type). |
http_response_code | Optional. Force the HTTP response code to the specified value. (Available in PHP 4 and later versions)} |
Tips and Comments
Note:From PHP 4.4 onwards, this function prevents the sending of multiple headers at once. This is a protective measure against header injection attacks.
Example
Example 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> ... ...
Note:Users may set some options to change the browser's default cache 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 a save dialog):
<?php header("Content-type:application/pdf"); // The file will be called downloaded.pdf header("Content-Disposition:attachment;filename='downloaded.pdf'"); // PDF source is in original.pdf readfile("original.pdf"); ?> <html> <body> ... ...
Note:Microsoft IE 5.5 has a bug that prevents the above mechanism. This bug can be resolved by upgrading to Service Pack 2 or a higher version.