PHP Http Headers - redirection, compression, caching, cookie


HTTP Headers
As we mentioned at the beginning of the blog, the server responds to an HTTP request by first sending a set of response headers that contain various tidbits of information about the data that is to follow, as well as other details of the transaction. These are simple strings in the form key: value, terminated by a newline character. The headers are separated by the content by an extra newline.
Although PHP and your web server will automatically take care of sending out a perfectly valid set of response headers, there are times when you will want to either overwrite the standard headers or provide new ones of your own.
This is an extremely easy process—all you need to do is call the header() function and provide it with a properly-formed header. The only real catch (besides the fact that you should only output valid headers) is in the fact that header() must be called before any other output, including any whitespace characters outside of PHP tags, as well as all HTML data and PHP output. If you fail to abide by this rule, two things will happen: your header will have no effect, and PHP may output an error.
Redirection
The most common use of headers is to redirect the user to another page. To do this, we use the Location header:

header("Location: http://phparch.com");

Note that the header redirection method shown here merely requests that the client stop loading the current page and go elsewhere—it is up to the client to actually do so. To be safe, header redirects should be followed by call to exit() to ensure that portions of your script are not called unexpectedly:

header("Location: http://phparch.com");
exit();

Compression
HTTP supports the transparent compression and decompression of data in transit during a transaction using the gzip algorithm.
Compression will make a considerable impact on bandwidth usage—as much as a 90% decrease in file size. However, because it is performed on the fly, it uses up many more resources than a typical request.
The level of compression is configurable, with 1 being the least compression (thus requiring the least amount of CPU usage) and 9 being the most compression (and highest CPU usage). The default is 6.
Turning on compression for any given page is easy, and because the browser’s Accept headers are taken into account, the page is automatically compressed for only those users whose browsers can handle the decompression process:

ob_start("ob_gzhandler");

Placing this line of code at the top of a page will invoke PHP’s output buffering mechanism, and cause it to transparently compress the scr ipt’s output.
You can also enable compression on a site-wide basis by changing a few configuration directives in your php.ini file:

zlib.output_compression = on
zlib.output_compression_level = 9

Notice how this approach lets you set the compression level. Since these settings can be turned on and off without changing your code, this is best way of implementing compression within your application.

Caching
By default, most browsers will attempt to cache as much of the content they download as possible. This is done both in an effort to save time for the user, and as a way to reduce bandwidth usage on both ends of a transaction.
Caching, however, is not always desirable, and it is sometimes necessary to instruct a browser on how to cache the output of your application in a non-standard way.
Cache manipulation is considered something of a black art, because all browsers have quirks in how they handle the instru ctions sent them by the server. Here’s an example:

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Thu, 31 May 1984 04:35:00 GMT");

This set of headers tells the browser not to cache the item at all by setting a cache expiration date in the past. Sometimes, however, you might want to tell a browser to cache something for a finite length of time; for example, a PDF file generated on the fly may only contain “fresh” information for a fixed period of time, after which it must be reloaded. The following tells the browser to keep the page in its cache for 30
days:

$date = gmdate("D, j M Y H:i:s", time() + 2592000); // 30 Days from now
header("Expires: " . $data . " UTC");
header("Cache-Control: Public");
header("Pragma: Public");

Cookies
To set a cookie on the client, you can use the setcookie() function:

setcookie("hide_menu", "1");

This simple function call sets a cookie called “hide_menu” to a value of 1 for the remainder of the users browser session, at which time it is automatically deleted. Should you wish to make a cookie persist between browser sessions, you will need to provide an expiration date. Expiration dates are provided to setcookie() in the UNIX timestamp format (the number of seconds that have passed since January 1, 1970). Remember that a user or their browser settings can remove a cookie at any time—therefore, it is unwise to rely on expiration dates too much.

setcookie("hide_menu", "1", time() + 86400);

This will instruct the browser to (try to) hang on to the cookie for a day. There are three more arguments you can pass to setcookie(). They are, in order:
·         path—allows you to specify a path (relative to your website’s root) where the cookie will be accessible; the browser wil l only send a cookie to pages within this path.
·         domain—allows you to limit access to the cookie to pages within a specific domain or hostname; note that you cannot set this value to a domain other than the one of the page setting the cookie (e.g.: the host www.phparch.com can set a cookie for hades.phparch.com, but not for www.microsoft.com).
·         secure—this requests that the browser only send this cookie as part of its request headers when communicating under HTTPS.

Accessing Cookie Data
Cookie data is usually sent to the server using a single request header. The PHP interpreter takes care of automatically separating the individual cookies from the header and places them in the $_COOKIE superglobal array:

if ($_COOKIE[’hide_menu’] == 1) {
// hide menu
}

Cookie values must be scalar; of course, you can create arrays using the same array notation that we used for $_GET and $_POST:

setcookie("test_cookie[0]", "foo");
setcookie("test_cookie[1]", "bar");
setcookie("test_cookie[2]", "bar");

At the next request, $_COOKIE[’test_cookie’] will automatically contain an array. You should, however, keep in mind that the amount of storage available is severely limited—therefore, you should keep the amount of data you store in cookies to a minimum, and use sessions instead.

There is no way to “delete” a cookie—primarily because you really have no control over how cookies are stored and managed on the client side. You can, however, call setcookie with an empty string, which will effectively reset the cookie:


setcookie("hide_menu", false, -3600);

Share this

0 Comment to " PHP Http Headers - redirection, compression, caching, cookie "

Post a Comment