What is a cookie? Limitations of cookie? Permanent cookie?

Cookie - A cookie is a piece of data that is stored on a user's browser. Thus, a cookie does not use any server memory. It is actually a small text file which is created by the broswer on the hard disk of the user. It is actually a piece of information in the form of text strings. A web server sends a cookie to a user (client browser) and then the browser stores it. A cookie is used to store information of a user & information about a user's preferences. How does the cookie works? - When a user visits a site, say, and creates a profile out there, the server sends an ID (basically an ID to track this user) and saves the ID through the user's browser in the form of a cookie on the user's system. When the user revisits this site, the website tracks the user's system for the existence of any cookie, and in case it finds a cookie, it customizes the site based on the user's settings and preferences. Now lets talk about how to create a cookie in ASP.NET. It is pretty simple. There is a class in the System.Web namespace by the name HttpCookie. This class may be used to easily create a cookie on the user's system. Below is a code sample on how to use a cookie in ASP.NET ...

//Creating a cookie

HttpCookie sampleCookie = new HttpCookie("UserColorSetting");
sampleCookie.Values.Add("Background", txtBackgroundColor.Text);
sampleCookie.Expires = #12/31/2010#;

//Getting a cookie value from the user's computer
String sGetCookie;
sGetCookie = Request.Cookies("UserColorSetting")("Background").ToString();

Limitations of Cookies - Cookies are meant for infrequent storage of small pieces of information. They are not meant as a normal communication or mechanism. Note that web browsers are not required to save more than 300 cookies total, nor more than 20 cookies per web server (for the entire server, not just for the page or site on the server), nor to retain more than 4 kilobytes of data per cookie (both name and value count towards this 4 kilobyte limit). The biggest limitation of these is the 20 cookies per server limit, and so it is not a good idea to use a different cookie for each variable that has to be saved. Rather save a single cookie containing a lot of information.

No comments: