Backup of the original page by Frank Boumphrey:
www.hypermedic.com/php/index.htm
Please consult the original if still available.
Using "Cookies" is the first method to maintain state that we shall look at. As mentioned in the previous section, cookies are simply text strings that are maintained on the clients computer. If a client has more than one web browser, each browser will maintain a separate set of cookies.
Where cookies are stored:
To look at the cookies stored on your computer: for IE5 on Windows 9* go toc:\windows\cookies; on Win2000 go toc:\Documents and Settings\user\cookies; for Netscape on Windows look forcookies.txtin thePrograms\Netscapefolder; on UNIX look in$HOME/netscape.
When a client requests a web page from a domain, it looks in it's 'cookie
jar' to see whether that domain has set any cookies. If it has it will send
a list of the cookies in the HTTP headers. In PHP this list can be accessed
using the $HTTP_COOKIE_VAR[] array.
Cookies are useful for storing small amounts of information on the client. Persistent cookies can be used to personalize a page when a user reaches a web site. Either the direct information can be used, or a reference to a database on the server can be made. Cookies can also be used for storing information that will just last the viewing session.
A session begins when a Client accesses a specific domain. It ends when the client closes down their Browser.
A cookie contains the following information:
"www.boumphrey.com/style/apage.php" would be accessible to "www.boumphrey.com/style/anotherpage.php" but not to "www.boumphrey.com/courses/apage.php". If you want to send a cookie in a subdirectory that can be read by the whole domain set the path value to "/".Usually only the first two or three items are set in a cookie.
Cookies are set with the setcookie() function. It takes six parameters, name, value, expires (a UNIX time stamp), path, domain, and secure. The syntax for setting a cookie is very straight forward. The data type is given in italics after the name
setcookie([name string],[value string],[expires UNIX time stamp],[path string],[domain string],[name integer])
The UNIX epoch was deemed to have started on (January 1 1970 00:00:00 GMT). The function time()returns the current time measured in the number of seconds since the UNIX Epoch (January 1 1970 00:00:00 GMT). It is known as a UNIX timestamp.
The following example sets 2 cookies. The first cookie will expire in an hour, the second will last for the duration of the current browser session.
1 <? 2 //the following code prevents the page from being cached 3 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past 4 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified 5 header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 6 header("Cache-Control: post-check=0, pre-check=0", false); 7 header("Pragma: no-cache"); // HTTP/1.0 8 //set the cookies 9 setcookie("fname","Frank",time()+3600); 10 setcookie("lname","Boumphrey"); 11 ?> 12 <html> 13 <title>PHP Cookies 1</title> 14 <p>Setting cookies</p> 15 </html>
<html>.
The reason we want to stop caching of the page, is because the browser when
delivered the page will figure that it is unchanged from the previous page.
(Remember it is not sent the PHP code), and thus will just serve up the old
page. The following line of code would set the above parameters in addition to those set already
setcookie("fname","Frank",time()+3600,"/",boumphrey.com",1)
Now the cookie would only be sent to secure pages (Those using SSL encryption),
but they would be sent to every page under the current domain name, and they
would also be sent to every page under the boumphrey.com domain name (providing boumphrey.com resides on the same server)
Setting cookies was remarkably easy! How do we retrieve them? Cookies
are sent to privileged pages in the in the header as an environmental array
variable $HTTP_COOKIE_VARS[]. This is an associative array where the Key to the environmental array variable is the cookie name. This will return the cookie value.
However
PHP allows you to access the cookie simply by using it as a variable! This
means if you have a cookie called 'lastname', putting <?=$lastname?>$lastname a value other than the cookie value using a form, you must specifically do so as follows.
// a cookie named "lastname" has the value of "Roe"
//This page has recieved a POST value with the name of lastname and a value of "Doe"
echo $lastname; //will print "Roe"
$lastname=$HTTP_POST-VARS["lastname"];
echo $lastname; //will now print "Doe"
In order to read the value of a specific named cookie we just insert the name as the key of the $HTTP_COOKIE_VARS[] array. Remember that we are dealing with an associative array. See Example 2. On the other hand we can just use the variable with the cookies name!
//The following will print out the value of the cookie named 'lastname'
echo $HTTP_COOKIE_VARS["lastname"];
//so will this!!
echo $lastname;
In order to retrieve a full list of the cookies, all we have to do is iterate through the $HTTP_COOKIE_VARS[] array. we do this in Example 2 below.
The following example will print out one specific cookie value (The "lastname" value), and then it will iterate through the cookies collection that was returned in the header to make a table of the names and values of all the cookies in the collection
1 <? 2 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past 3 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified 4 header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1 5 header("Cache-Control: post-check=0, pre-check=0", false); 6 header("Pragma: no-cache"); // HTTP/1.0 7 ?> 8 <html> 9 <title>PHP Cookies 1a</title> 10 <p>Retrieving cookies</p> 11 <? 12 echo "Print out the value of the \"lastname \" cookie:-"; 13 echo "<b>".$HTTP_COOKIE_VARS["lastname"]."</b><br />"; 14 echo "<p>There are ". count($HTTP_COOKIE_VARS)." cookies stored for this domain.</p>"; 15 echo "<table border='1' cellpadding='5'>"; 16 echo "<tr><th>Cookie Name</th><th>Cookie Value</th></tr>"; 17 for ($i=0;$i < count($HTTP_COOKIE_VARS);$i++) 18 { 19 echo "<tr><td>".key($HTTP_COOKIE_VARS)."</td><td>".current($HTTP_COOKIE_VARS)."</td></tr>"; 20 next($HTTP_COOKIE_VARS); 21 } 22 echo "</table>"; 23 ?> 24 </html>
<html>.
The reason we want to stop caching of the page, is because the browser when
delivered the page will figure that it is unchanged from the previous page.
(Remember it is not sent the PHP code), and thus will just serve up the old
page. $HTTP_COOKIE_VARS[] is an associative
array. The Key is the cookie name, so when we pass it the value of the key,
i.e. the cookie name, it will return the value.count() function to get the number of cookies in the $HTTP_COOKIE_VARS[] array.key() and current() functions to print out the name and the value of the cookie in a table.To alter a cookie we simply use the setcookie() function to pass new parameters to a cookie of the same name.
// change the value of fname cookie to Francis,and persist it for a year!
//old values : - setcookie("fname","Frank",time()+3600,"/",boumphrey.com",1)
setcookie("fname","Francis",time()+(3600*24*365),"/",boumphrey.com",1)
To delete a cookie simply set the expires date to a date in the past!
// delete this cookie
//old values : - setcookie("fname","Frank",time()+3600,"/",boumphrey.com",1)
//set to a date an hour ago
setcookie("fname","Francis",time()-(3600),"/",boumphrey.com",1)
By default, a cookie can beaccessed by the document that created the cookie, and by documents residing in the same folder, or in any descendant folders. If the path and domain values have been set then the cookie will be read by documents who meet these criteria.
Cookies are a very valuable part of an internet programmers armourmentarium. However they do have limitations, chief of which are:
Clients can also switch off Cookies on their browsers. For all these reasons cookies should be used sparingly in HTML applications.
Have a look at the simple application that we have created to personalize a web page.
İFrank Boumphrey 2001