A Quick Note About header()
I've seen a great many questions come in lately on the use of the header() function in PHP. This is just a quick note to describe it's use and some of the issues surrounding it.
There are two basic types of headers when we talk about HTTP Header directives. Request Headers and Response Headers. Request headers are what your browser sends to a server, and response headers are what the server sends back. I've seen more complicated explanations, and they are accurate, but that's the essence of the thing.
When you specify a header with the header() function in PHP, you're sending a response header from the server 99.9% of the time. Most of the time, you're trying to use a header to:
- Relocate to a different page
- Download a file
Headers can be used for a number of different things, including setting cookies, but we're not going to look at that in this article. The cookie functions in PHP can handle everything you want to do with cookies.
Relocation:
When you're relocating to a different page from PHP, the function you use looks like this:
Which will send that header to the browser, causing it to head over to page.php on the somesite.com domain. So, you enter it into your code, and everything works, right?
Well, not always. See, when you don't specify any headers but send output to the browser (with print(), echo(), or just standard HTML), PHP is smart enough to send it's own. (PERL, not so much, but that's a different story). So when you've output anything, including whitespace to the browser, you get message telling you Headers have already been sent.
If you're not sure why, and you haven't output anything to the browser on purpose before the headers you're sending, the first thing to do is check for whitespace right before your opening PHP tag in your code. Resolve that there is none first.
If you want a little cleaner solution, you can use ob_start() and ob_flush() to send everything into an output buffer before it gets to the browser, and have it sent all at once.
One caveat here is that you want to call ob_flush() as soon as possible, because on scripts with large output, you can slow things down considerably.
Example without output buffers:
exit() in the above example stops the script so nothing else will be executed. Without it, you can have the unintended consequence of doing something after you meant to redirect the user to a different page.
Example with output buffering:
~A!