Headers: Explained
We've all seen them at one point or another in our PHP programming-lives. They usually come before all output or within the code if we use output buffering. They are used to send HTTP Headers to the browser, the same headers you see if you capture a HTTP Challenge/Response.
You can find more information about the HTTP Protocall at 'http://www.w3.org/Protocols/Specs.html'. It is suggested that for a degree of compliance with up-and-coming trends you use the HTTP/1.1. Changes, updates, and erratas can be found in the RFC (Requests for Comments) which are like form-posts for an organization like the w3c.
You Must Follow Two Basic Rules When Use Header:
1. Header() Can Only Be Used BEFORE Output is Sent to the Browser
2. All Parameters passed to Header() must follow HTTP specs.
void header ( string string [, bool replace [, int http_response_code]] )
The first (and only required argument) is the HTTP Header you wish to send, which must conform to the HTTP Sepcs. The second is irrevelant to this discussion. And the third is a integer-HTTP response code you wish to force the client to accept. Both the second and third arguments are optional.
A few common uses of headers are to redirect the browser and force the browser to download a file.
[highlight="php"]
<?php
header("Location: http://www.abc.com"); # Redirect the browser
?>
[/highlight]
Please note that the HTTP/1.1 RFC's state that the Location: header MUST contain a valid protocall, hostname, and absolute path to the file or directory
You May use the
[highlight="php"]
<?php
header("Content-Type: xxx/xxxx");
header("Content-Disposition: attachment; xxxx");
readfile(xxx);
?>
[/highlight]
to force the browser to download a file. You must replace the X's with valid meta-types and file name for the file you wish to download.
You can check to see if headers have been sent by using 'headers_sent()'
[highlight="php"]
<?php
header("Content-Type: text/html");
if (headers_sent()) {
echo "True";
} else {
echo "False";
} # Will echo 'True'
?>
[/highlight]
I hope you got something out of this tutorial, and look out for a tutorial on Output Buffering, a neat way to circumvent the header rules.
"Yeah, so, umm.., I wanted to get my girlfriend out of work so I called in a bomb threat, but I got caught..."
From 104.1's 'It seemed like a good idea at the time' segment