To use this website fully, you first need to accept the use of cookies. By agreeing to the use of cookies you consent to the user of functional cookies. For more information read this page.

HTTP headers in PHP

PHP being a server side scripting language can interact with web servers in many ways. One of those is through the use of HTTP headers.

HTTP headers are ways of sending information that describes the content of the HTML (or other type of file). For instance, a HTTP header request for http://www.jamiebalfour.com/ looks like:

HTTP
Connect to 108.175.157.32 on port 80 ... ok
GET / HTTP/1.1[CRLF]
Host: jamiebalfour.com[CRLF]
Connection: close[CRLF]
User-Agent: Web-sniffer/1.1.0 (+http://web-sniffer.net/)[CRLF]
Accept-Encoding: gzip[CRLF]
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
Cache-Control: no-cache[CRLF]
Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]
Referer: http://web-sniffer.net/[CRLF]
		

Headers in PHP

PHP allows the manipulation of headers using the header function.

HTTP
<?php
	header($headerString);
?>
		

The $headerString is used to define the header information that would be sent. For instance, a PHP redirect to http://www.jamiebalfour.com/ could be specified with:

HTTP
<?php
	header("Location: http://www.jamiebalfour.com/");
?>
		

There are several other PHP supported headers which are described in the table below:

Header Purpose
Cache-Control: no-cache, must-revalidate Prevents caching of a page
Content-Type: application/pdf Modify the content type and get PHP to 'fake' it's file type.
Content-Disposition: attachment; filename="file.pdf" Modify the header file name when a file is being downloaded. This way the file can be given it's original name.

Things to observe with headers

HTTP headers absolutely must be defined before any output is given out. That means that the header must be before any HTML or text. This even includes whitespace that is not within the PHP block.

Without following this rule, PHP may throw errors or warning on to the page as well.

Files with headers should absolutely not store with a byte-order-mark (BOM). The byte-order-mark that will appear normally appears as the hexadecimal EF BB BF. There is more on this here.