Using HTTP Cookies to Link Transactions

Now that you've wolfed down the pizza, it's time for some dessert. However, the cookies that we'll be digesting in this section are not made with chocolate chips. Cookies are used to store information on our customers' hard disks. In the EX35A example, the server stores the customer name in a hidden field of the confirmation form. That works fine for linking the confirmation to the order, but it doesn't help you track how many pizzas Walter ordered this year. If you notice that Walter consistently orders pepperoni pizzas, you might want to send him some e-mail when you have a surplus of pepperoni.

How Cookies Work

With cookies, you assign Walter a customer ID number with his first order and make him keep track of that number on his computer. The server assigns the number by sending a response header such as this one:

Set-Cookie: customer_id=12345; path=/; expires=Monday, 
    02-Sep-99 00:00:00 GMT

The string customer_id is the arbitrary cookie name you have assigned, the / value for path means that the browser sends the cookie value for any request to your site (named CyberPizza.com), and the expiration date is necessary for the browser to store the cookie value.

When the browser sees the Set-Cookie response header, it creates (or replaces) an entry in its cookies.txt file as follows:

customer_id
12345
cyberpizza.com/
0
2096697344
0
2093550622
35
*

Thereafter, when the browser requests anything from CyberPizza.com, the browser sends a request header like this:

Cookie: customer_id=12345

How an ISAPI Server Extension Processes Cookies

Your ISAPI server extension function makes a call like this one to store the cookie at the browser:

AddHeader(pCtxt, "Set-Cookie: session_id=12345; path=/;"
     " expires=Monday, " 02-Sep-99 00:00:00 GMT\r\n");

To retrieve the cookie, another function uses code like this:

char strCookies[200];
DWORD dwLength = 200;
pCtxt->GetServerVariable("HTTP_COOKIE", strCookies, &dwLength);

The strCookies variable should now contain the text customer_id=12345.

Problems with Cookies

There was an uproar some time ago when Internet users first discovered that companies were storing data on the users' PCs. New browser versions now ask permission before storing a cookie from a Web site. Customers could thus refuse to accept your cookie, they could erase their cookies.txt file, or this file could become full. If you decide to use cookies at your Web site, you'll just have to deal with those possibilities.