PHP and Cookies - Creating, Reading and Writing

From Techotopia
Revision as of 14:44, 6 June 2007 by Neil (Talk | contribs)

Jump to: navigation, search

Web servers are typically stateless entities. That is to say they serve up web pages without regard to who requested the page and with no knowledge of whether that person has previously requested other pages. This makes it difficult for web based applications to track whether a visitor is new to the site or whether they have visited before and have already logged into a service. Cookies were developed to provide a mechisms to track state in the otherwise stateless world of the web.

Cookies essentially provide a mechanism to store small pieces of data on the computer systems of the visitors to your site. This enables you to maintain the state of a user's visit to your site so that you can track their movement through though the site, or to store information such as their user name and address after they have entered it on one page so that they don't have to keep re-entering it on different pages.

Another option for maintaing state is to use PHP Sessions (see Understanding PHP Sessions for more information). Cookies and sessions differ in important ways, and which to use depends on your requirements.


Contents


The Difference Between Cookies and PHP Sessions

The Structure of a Cookie

Cookies allow data to be stored in the form a name/value pair. Both the name and the value are set at your discretion. For example you might want to write a cookie that store the user name in the from username=JohnW. The cookie also contains additional information usch as an expiration date and a domain.

The format of a cookies is as follows:

name=value; expires=expirationDateGMT; path=URLpath; domain=siteDomain

Cookie Name / Value Pair

The first section of the cookie defines the name of the cookie and the value assigned to the cookie. As previously mentioned, both the name and value settings can be anything you choose to use. For example, you might want save a user's currency preference - currency=USDollars. This is the only section of the cookie that is mandatory, the rest are entirely optional. Whether or not you use these optional settings depends on your specific requirements. The following settings, therefore, can be omitted from the cookies if they are not required.

Cookie Expiration Setting

The optional expires= section specifies the date on which the associated cookie should expire. The PHP time() function can be used to obtain and manipulate dates for this purpose as we will examine later in this chapter.

Cookie path Setting

The path= setting allows a URL to be stored in the cookie. By default, cookies are accessible only to web pages in the same directory as the web page which originally created the cookie. For example, if the cookie was created when the user loaded http://www.techotopia.com/intro/index.html that cookie will be accessible to any other pages in the /intro directory, but not to pages in /navigation. By specifying path=/navigation this limitation is removed.

Cookie domain Setting

Similar to the path setting, cookies are only accessible to web pages residing on the server domain from which the cookie was originally created. For example, a cookie created by a web page residing on www.techotopia.com is not, by default, accessible to a web page hosted on www.linuxtopia.org. Access to the cookie from web pages on linuxtopia.org can be enabled with a domain=linxutopia.org setting.

Cookie Security Setting

This setting controls whether the cookie is transmitted using insecure HTTP or secure HTTPS.

Creating a Cookie in PHP

Cookes are created in PHP using the setcookie() function. setcookie() takes a number of arguments. The first argument is the name of the cookie (the name part of the name/value pair described earlier). The seconmd is the value part of the name/value pair. The third argument is the optional expiration date of the cookie. The fourth argument specifies the active path for the cookie. The fifth argument is the domain setting and the sixth is the security setting (0 specifies HTTP and HTTPS and 1 specifies HTTPS only).

Based on the above information we can create a cookie using the following PHP:

<?php
       setcookie('username', 'JohnW', time() + 4800);
       echo 'Cookie has been set<br>';
?>

The above example creates a cookie on the computer system of anyone who loads the page (assuming they have cookies enabled in their browser) containing the name value pair userName=JohnW'. The cookie will expire 4800 seconds from the time it is created.

Reading a Cookie in PHP

Gven that you've gone to the trouble of writing a cookie it stands to reason you'll probably want to read it back at some point. This is achieved by accessing the $_COOKIE array. The $_COOKIE array is an associative array whereby the name of the cookie provides the index into the array to extract the corresponding value of the name/value pair (for details of PHP arrays read the PHP Arrays chapter of this book.

For example we can obtain the value of our userName cookie as follows:

';
       echo 'Reading cookie<br>';

       echo 'userName = ' . $_COOKIE['userName'];
?>

The above script should generate the following output:

Cookie has been set
Reading cookie
userName = JohnW