The header() function sends raw HTTP headers to the client.
It's important to realize that the header() function must be called before any actual output is sent (in PHP 4 and later, you can use output buffering to solve this problem):
<html><?php// This results in an error.// The output above is before the header() callheader('Location: http://www.example.com/');?>
header(string,replace,http_response_code)
parameter | describe |
---|---|
string | Required. Specifies the header string to be sent. |
replace | Optional. Indicates whether this header replaces the previous header, or adds a second header. Default is TRUE (replacement). 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 above) |
Note: Since PHP 4.4, this function prevents multiple headers from being sent at once. This is a protection measure against header injection attacks.
Disable page caching:
<?php// Date in the pastheader("Expires: Mon, 26 Jul 1997 05:00:00 GMT");header("Cache-Control: no-cache");header("Pragma: no-cache") ;?><html><body>......
Note: There are options that users may set 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!
Prompt the user to save a generated PDF file (the Content-Disposition header is used to provide a recommended file name and force the browser to display a save dialog):
<?phpheader("Content-type:application/pdf");// It will be called downloaded.pdfheader("Content-Disposition:attachment;filename='downloaded.pdf'");// The PDF source is in original .pdfreadfile("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 higher.