What Are Cookies?
Written on 09/08/09 at 00:41:05 EST by Admin
InternetA cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.

Imagine that when users request a page from your site, www.contoso.com, your application sends not just a page, but a cookie containing the date and time. When the user's browser gets the page, the browser also gets the cookie, which it stores in a folder on the user's hard disk.

Later, the user requests a page from your site again. When the user enters the URL www.contoso.com, the browser looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site. You might use the information to display a message to the user, check an expiration date, or perform any other useful function.

Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange the www.contoso.com cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately.

That's the basics of how cookies work. But what are they good for? In essence, cookies help Web sites store information about visitors. More generally, cookies are one way of maintaining continuity in a Web application (formally, performing state management). Except for the brief time when they are actually exchanging information, the browser and Web server are disconnected. Each request you make to a Web server is treated independently of any other request. Many times, however, it's useful for the Web server to recognize you when you request a page. For example, the Web server on a shopping site' keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting pertinent identification that helps an application know how to proceed.

Cookies are used for all sorts of purposes, all relating to helping the Web site remember you. For example, a site conducting a poll might use a cookie simply as a Boolean value to indicate whether your browser has already participated in voting so that you don't vote twice. A site that asks you to log on might use a cookie to tell itself that you've already logged on so that you don't have to keep entering your credentials.

If you'd like more background information about cookies, I recommend an article called "How Internet Cookies Work" on the Verizon Web site at http://www22.verizon.com/about/community/learningcenter/articles/displayarticle1/0,4065,1022z1,00.html. The author goes into detail about what cookies are and how they are exchanged between browser and server. He also includes a good summary of what the privacy concerns are about cookies.

Incidentally, have you ever wondered why they are called "cookies"? The Jargon File (aka The New Hacker's Dictionary), version 4.2.2, has a good definition and a plausible explanation of the term's etymology. You can find the entry at http://www.catb.org/~esr/jargon/.

Before we start on the mechanics of working with cookies, I will mention a couple of limitations of working with cookies. Most browsers support cookies of up to 4096 bytes. That is plenty of space for storing a few values on the user's computers, but you would not want to try to store a dataset or some other potentially large piece of data in a cookie. More practically, you probably do not want to store a big collection of user information in a cookie. Instead, you would want to store a user number or other identifier. Then, when the user visits your site again, you would use the user ID to look up user details in a database. (But see Cookies and Security for some caveats about storing user information.)

Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.

A cookie limitation that you are likelier to run into is that users can set their browser to refuse cookies. You cannot do much to get around this problem except to avoid cookies altogether and use a different mechanism to store user-specific information. A common method for storing user information is Session state, but Session state depends on cookies, as I explain later in Cookies and Session State.

The more general lesson is probably that although cookies can be very useful in your application, the application should not depend on being able to store cookies. Use cookies for nice-to-have features; do not use them to support critical features. If your application must rely on cookies, you can test to see whether the browser will accept cookies.

You write a cookie using the page's Response property, which exposes an object that allows you to add to the information being rendered to the browser by the page. The Response object supports a collection named Cookies, to which you add the cookies you want to write to the browser.

Note   The Response object and the Request object, which I will discuss shortly, are properties of the page that contain, respectively, instances of the HttpResponse and HttpRequest classes. To find information in the documentation about Response and Request, look under HttpResponse and HttpRequest.
When you create a cookie, you specify several values. To start with, you specify the name of the cookie and the value to store in it. You can create multiple cookies, and each cookie must have a unique name so you can identify it later when you want to read it. (Cookies are stored by name, so if you create two cookies with the same name, one overwrites the other.)

You might also want to specify the cookie's expiration date and time. Cookies are normally written to the user's disk, where they could potentially hang around forever. You can therefore specify a date and time on which the cookie expires. When the user visits your site again, the browser first examines the collection of cookies for your site. If a cookie has expired, the browser does not send that particular cookie to the server with the page request; instead, the expired cookie is deleted. (Your site might have written multiple cookies to the user's computer; each cookie can have a separate expiration date and time.) Notice that the browser is responsible for managing cookies on the hard disk, a fact that affects what you can do with cookies in your application.

How long should the expiration period be for a cookie? It depends on what you're using the cookie for, or to put it another way, it depends on how long your application considers the cookie value to be valid. If you're using cookies to count visitors to your site, you might decide to set expiration to a year from now on the theory that if someone hasn't visited your site in a year, you can consider that user a new visitor. In contrast, if you use cookies to store user preferences, you might set the expiration to effectively never expire (expiration of 50 years, say), since a user might find it annoying to have to reset preferences periodically. You might sometimes write a cookie that expires in seconds or minutes. Later in the paper in the section Checking Whether a Browser Accepts Cookies I have an example that creates a cookie whose practical lifetime is measured in seconds.

Don't forget that users can clear the cookies on their computer any time. Even if you store cookies with long expiration times, a user might decide to delete all cookies, wiping out any settings you might have stored in cookies.

If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser or if the session times out, the cookie is discarded. A non-persistent cookie like this is handy for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer. For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.

News and Comments Brought to you by: Geeks and Bloggers
The comments are owned by the poster. We aren't responsible for its content.