Archive - Originally posted on "The Horse's Mouth" - 2007-05-30 05:27:35 - Graham Ellis
PHP's header function allows you to change the headers on your returned content so that (examples)
• The browser receives not HTML but plain text, a .jpg image or a file to save locally
example: header ('Content-type: Application/Octet-stream');
• You can change a "404" missing reponse code into a "200" - good.
example: header("HTTP/1.1 200 OK");
• You can send out cache instructions
example: header("cache-control: no-store");
• you can sent out a save file name if you're saving the file.
example: header ('Content-Disposition: attachment; filename="hello.txt"');
However, up until PHP 4.4.2 / PHP 5.1.2 it was prone to injection attacks. If you used a variable within the parameter and your user could set that variable to include a new line character, he could add in any other header at all.
As from the releases above, you should send separate header directives if you want to set multiple headers as PHP has been altered to take care of the potential security issue and is not backwards compatible over this.
There's an example in our "database download to local CSV file" demonstration with required to set both a content-type and a content-disposition. Have a look at the source code in which I have commented out the old and replaced it by the new. The old was producing a message like: Warning: Header may not contain more than a single header, new line detected. in C:\Domains[part of URL removed]testsite\phpcsv\phptocsv1.php on line 30
Note also with the header function - you may ONLY call it before your PHP script has sent out any content to the browser. This means that it must be in a block of PHP that comes at the very top of your script (no blank lines or spaces before the initial <?php please). See also the ob_start function which, however, I dislike.