HTTP Headers


Every page downloaded from a web server is a result of an exchange of HTTP dialogue. The web browser sends a set of instructions to indicate which page it wants to view, and the server responds with a response that indicates the success of the request, along with various other information that is not displayed directly on the web page.

The following HTTP headers show some of the information that is sent along with a typical web page from a PHP-enabled web server:

 HTTP/1.1 200 OK Date: Tue, 14 Dec 2004 21:17:28 GMT Server: Apache/1.3.29 (Unix) mod_gzip/1.3.26.1a PHP/4.3.9          mod_ssl/2.8.16 OpenSSL/0.9.7c X-Powered-By: PHP/4.3.9 Connection: close Content-Type: text/html; charset=iso-8859-1 

Sending Custom Headers

The PHP function to send a custom HTTP header is header. Let's start by sending a header that does nothing. Any header that begins with X is considered to be for information only; for example, the X-Powered-By header shows that PHP is enabled. To stamp your name in the HTTP headers in your script, you could use the following:

 header("X-PHP-Author: Chris Newman <chris@lightwood.net>"); 

Of course, there is no reason you should want to send a header like this, other than extreme vanity. A regular user browsing the website would never even see this header!

You have already seen how cookies are sent to a web browser by using the setcookie function. You have also seen that what happens when this function is called is that a Set-Cookie HTTP header is actually sent. The following two PHP statements are therefore equivalent:

 setcookie("mycookie", "somevalue"); header("Set-Cookie: mycookie=somevalue"); 

Redirection Headers

The header you will send most often is almost certain to be Location, which instructs the web browser to redirect to another URL. You can use this header to change the flow of a website according to events in script. Causing the user's browser to forward to another page is as simple as this:

 header("Location: anotherpage.php"); 

You can use either a relative or absolute URL in the Location header, so you could even forward the user to another domain, like so:

 header("Location: http://www.somedomain.com/newpage.php"); 

When a Location header has been sent, you should halt the script immediately, using exit, to make sure that no further output is sent to the browser.

Checking Whether Headers Have Been Sent

As soon as PHP hits the first piece of non-header output in a script, it makes sure all the necessary headers have been sent to the web browser and begins to work on the page itself. All the HTTP headers must be sent at once and must be sent before any of the web page output.

If the headers have already been sent for a script and you attempt to send another, PHP gives an error like this:

[View full width]

Warning: Cannot modify header information - headers already sent by (output started at /home/chris/ public_html/header.php:4)in /home/chris/ public_html/header.php on line 5

In the case of a Location header, you don't need to display anything on the page because the browser goes straight to the new URL. However, you still need to be careful to avoid any HTML output, and particularly whitespace, before the script begins; even a single carriage return before the opening <?php tag will prevent you from being able to send custom HTTP headers.

PHP provides the function headers_sent, which you can use to detect whether the HTTP headers have already been sent in that script. The function returns trUE if headers have been sent and FALSE if it is not too late to send additional custom headers.

The following condition makes sure the headers have not been sent before attempting to perform a redirection:

 if (!headers_sent()) {   header("Location: newpage.php"); } 

Of course, your script would still need to do something else if this condition failed.

Two optional arguments to headers_sent allow you to find out the script name and line number where the headers were sent. This is useful if your script is giving an error but you think that the headers have not been sent at that point.

Listing 16.1 attempts to perform a redirect by using a Location header, but if it fails, it displays the reason and an alternative way to get to the destination page. If you run this on your web server, you should add some whitespace or HTML at the top of the script, outside the <?php tags, to make sure the headers are sent prematurely.

Listing 16.1. Checking Whether Headers Have Been Sent
 <?php $destination = "http://www.lightwood.net/"; if (!headers_sent($filename, $line)) {   header("Location: $location"); } else {   echo "Headers were sent in line $line of $filename <br>";   echo "<A HREF=\"$destination\">Click here to continue</A>"; } ?> 

Displaying HTTP Headers

If you want to see which HTTP headers have been or will be sent, you use the headers_list function, which is available in PHP version 5 and above. This function returns an array that contains one header per element.

You can perform a loop on the array returned to grab each value in turn. However, in many cases, all you want to do is see the headers that are being output to check them over, and in this case, passing the array to print_r does the trick:

 print_r(headers_list()); 

You need to make sure to put <PRE> tags around this for readability. The following is typical output:

 Array (     [0] => X-Powered-By: PHP/5.0.2     [1] => Set-Cookie: mycookie=somevalue     [2] => Content-type: text/html ) 

Changing Cache Settings

You can use HTTP headers to change the cache settings for a web page, to determine whether a page is completely refreshed each time it is loaded or whether the user's browseror his or her ISPwill keep a local copy for a period of time to save downloading it from your website again.

You use the Cache-Control header to specify what caching scheme to use for a page. The primary control values for this header are shown in Table 16.1.

Table 16.1. Primary Cache-Control Settings

Value

Description

public

May be stored in any web cache.

private

May be saved to the browser's cache but may not be stored in a shared web cache.

no-cache

May not be stored in any cache between the web server and browser.


Usually the reason for overriding the default cache settings is to make sure that a page is fully refreshed every time it is visited.

In most cases, web caches detect that a PHP-generated page with changing content needs to be refreshed frequently, but to make absolutely sure that all your up-to-the-minute content is being displayed correctly around the world, you might want to give it a helping hand.

To make absolutely sure your page will not be cached, using the following statements, which send a number of headers, is generally considered to be the definitive way to prevent caching of any kind:

 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ". gmdate("D, d M Y H:i:s") . " GMT"); 

A few different headers are used here. Two Cache-Control headers are sent, including a no-cache instruction. You can find more information on the other, less common, Cache-Control settings at www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.

The Expires header tells the browser when a document goes out of date. If you send a historic date in this header, the document will always be considered to be old and need to be refreshed the next time it is viewed.

The Last-Modified header tells the browser how recently the document was modified. When you use the date function, this header always sends the current date, so the browser always thinks it has only just been modified and requests a new copy of the page in full.

Session Cache Control When a PHP session is started, no-cache headers are automatically sent, along with the other HTTP headers that establish the session. You can use a different cache setting by using the session_cache_limiter function, with one of the values in Table 16.1 as an argument.




    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net