Authenticate and Track Users with PHP
Page 5
Using Cookies (munch munch munch)
There's a phrase that's bandied about quite a bit: "The Web is a stateless environment." Basically, this means that a Web server doesn't know squat about the users accessing it, and unless your server-side programs tell it to care, it doesn't care. When your browser sends a request for a page, the Web server just sends the requested page on back to you and ends the relationship. But you can try to develop some cohesion among anonymous, seemingly random accesses by using cookies to hold some vital information. Use of cookies is also know as "maintaining state." That means if a server sends a cookie and your browser accepts it, then you have made a connection that will exist until that cookie expires. The Web server still won't know much about you, but it will at least know that it has seen you before and it liked you enough to let you stay.
These sorts of identification cookies are valuable in e-commerce sites, where you're creating a shopping system that allows you to store selected items until you're ready to pay for them. You can use cookies for all sorts of things, not just shopping carts, but the e-commerce example is popular, so we'll go with that one.
Before you go around setting cookies, decide how you're going to use them and at what point you're going to set them. Do you want to check for a cookie on every page of your site, setting one if a cookie doesn't already exist? How are you going to use the cookie data? Whatever cookies you decide to use, here's one very important aspect to remember: You MUST MUST MUST set a cookie before sending any other content to the browser. Remember that and you won't spend hours wondering why you're getting
header() errors!
For example, consider Ballgirl Athletic, a site I
created that designs and sells sports apparel exclusively for female
athletes. The site uses a single cookie, which contains a unique
user ID. A common chunk of code on every page checks for this cookie, and
if it doesn't exist, the cookie is set. This is necessary because, on each
page, there's a shopping cart icon and an indicator of the number of items
in the user's cart.
The first time users access any page on the site, they're assigned
random values as their user IDs. Every page starts off something like this: |
<?php
// set cookie if not already set
if (!isset($id)) {
srand((double)microtime()*1000000);
$randval = rand();
setcookie("id",$randval,time()+14400,"/",".ballgirl.com",0);
}
?>
That's all well and good, you say, but what the heck is all that? Well, the first two lines after the if statement seed the random number generator, which produces a value to use for the ID. This random number is usually something like 1404291115.
Next, we set the cookie:
|
setcookie("id",$randval,time()+14400,"/",".ballgirl.com",0);
The syntax of the setcookie() function in PHP is:
|
setcookie(name, value, expiration, path, domain, security);
In our cookie example, we are calling the cookie "id" and assigning it the value $randval. This particular cookie will expire in four hours (the current time plus 14,400 seconds). The cookie is valid for any page below the document root on the domain ballgirl.com.
To ensure that your cookie can be set and accepted by the wide variety of browsers, use some sort of value for each part of the cookie. Don't just skip the expiration or the path and hope it works out. You know that the minute you skip something "optional," the one browser that crashes will belong to the user who wants to buy $10,000 worth of stuff from your fledgling site. A good place to learn about the ins and outs of cookies is Netscape's preliminary cookie specification.
So a user accesses the site and gets a cookie with some sort of value in it. To use that value in subsequent pages, you can get it from the global PHP variable $HTTP_COOKIE_VARS. In our example above, we extract the value of "id" from the cookie using:
|
$id = $HTTP_COOKIE_VARS["id"]
At Ballgirl Athletic, the values of id cookies are written to a database when users add items to their shopping carts, which are actually database tables that looks something like this:
+-------------+----------+----------+----------------+-----------+
| id | item_id | item_qty | item_color | item_size |
+-------------+----------+----------+----------------+-----------+
| 1404291115 | BG_LPR | 1 | Teal/Navy Blue | OSFA |
+-------------+----------+----------+----------------+-----------+
As users add more and more items to their carts, the item count displayed on each page will change, because it's generated each time the page is accessed. To get the number of items associated with a user ID, we'll use an SQL statement:
|
$sql = "select sum(item_qty) from db_table where id='$id'";
Somewhere in your code, before the section that displays the count, we'll need to get the count:
|
<?php
$id = $HTTP_COOKIE_VARS["id"]
// connect to MySQL
mysql_connect("hostname", "username", "password")
or die ("Unable to connect to database.");
// select database on MySQL server
mysql_select_db("dev_i2ii_com")
or die ("Unable to select database.");
// prepare SQL statement
$sql = "select sum(sel_item_qty) from db_table where id='$id'";
// query DB using SQL statement
$item_result = mysql_query($sql);
// assign value to variable called $item_count
$item_count = mysql_result($item_result,0,"sum(item_qty)");
?>
When you're ready to display the number of items in this particular user's shopping cart, just echo back the value of $item_count:
|
echo "Cart contains: $item_count items.";
Or, to be grammatically correct about it:
|
if ($item_count == "1") {
echo "Cart contains: $item_count item.";
} else {
echo "Cart contains: $item_count items.";
}
In our cookie-setting example, we set a cookie that expired after four hours. If you don't want your cookies to expire at any particular time but rather when users explicitly log out of your system (via a Logout button, for example), you can effectively delete cookies by sending cookies with the same name that have a blank value.
Say you've set a cookie:
|
setcookie("valid_user","yes",time()+14400,"/",".yourdomain.com",0);
The name of this cookie is "valid_user" and the value is "yes." To delete this cookie, have your script send a nearly identical cookie; the only change is that the value will be an empty string (""):
|
setcookie("valid_user","",time()+14400,"/",".yourdomain.com",0);
This process effectively deletes the cookie. No more valid user!
|
next page»
|
|