PHP header()
Function
Definition and Usage
The header()
function sends a raw HTTP header to the client.
It is important to note that the header()
function must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP (in PHP 4 and later, you can use output buffering to address this issue):
Syntax
Parameter | Description |
---|---|
string | Required. Specifies the header string to send. |
replace | Optional. Indicates whether the header should replace a previous similar header, or add a second header of the same type. Default is TRUE (replace). FALSE (allow 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 later) |
Tips and Notes
Note: After PHP 4.4, this function prevents more than one header from being sent at once. This is a protection against header injection attacks.
Example 1
Disable page caching:
Note: Users may set some options to change their browser's default cache settings. By sending the header above, 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 file name and to force the browser to display the save dialog):
Note: There is a bug in Microsoft IE 5.5 that prevents this mechanism from working. It can be resolved by upgrading to Service Pack 2 or later.