Previous Section  < Day Day Up >  Next Section

Chapter 8. Remembering Users with Cookies and Sessions

A web server is a lot like a clerk at a busy deli full of pushy customers. The customers at the deli shout requests: "I want a half pound of corned beef!" and "Give me a pound of pastrami, sliced thin!" The clerk scurries around slicing and wrapping to satisfy the requests. Web clients electronically shout requests ("Give me /catalog/yak.php!" or "Here's a form submission for you!"), and the server, with the PHP interpreter's help, electronically scurries around constructing responses to satisfy the requests.

The clerk has an advantage that the web server doesn't, though: a memory. She naturally ties together all the requests that come from a particular customer. The PHP interpreter and the web server can't do that without some extra steps. That's where cookies come in.

A cookie identifies a particular web client to the web server and to the PHP interpreter. Each time a web client makes a request, it sends the cookie along with the request. The interpreter reads the cookie and figures out that a particular request is coming from the same web client that made previous requests, which were accompanied by the same cookie.

If deli customers were faced with a memory-deprived clerk, they'd have to adopt the same strategy. Their requests for service would look like this:

"I'm customer 56 and I want a half-pound of corned beef."

"I'm customer 29 and I want three knishes."

"I'm customer 56 and I want two pounds of pastrami."

"I'm customer 77 and I'm returning this rye bread -- it's stale."

"I'm customer 29 and I want a salami."

The "I'm customer so-and-so" part of the requests is the cookie. It gives the clerk what she needs to be able to link a particular customer's requests together.

A cookie has a name (such as "customer") and a value (such as "77" or "ronald"). Section 8.1, next, shows you how to work with individual cookies in your programs: setting them, reading them, and deleting them.

One cookie is best at keeping track of one piece of information. Often, you need to keep track of more about a user (such as the contents of their shopping cart). Using multiple cookies for this is cumbersome. PHP's session capabilities solve this problem.

A session uses a cookie to distinguish users from each other and makes it easy to keep a temporary pile of data for each user on the server. This data persists across requests. On one request, you can add a variable to a user's session (such as putting something into the shopping cart). On a subsequent request, you can retrieve what's in the session (such as on the order checkout page when you need to list everything in the cart). Later in this chapter, Section 8.2 describes how to get started with sessions, and Section 8.3 provides the details on working with sessions.

    Previous Section  < Day Day Up >  Next Section