RadianT tutorials, tips and tricks

About cookies

Posted on 2008-Jan-28 at 06:28 in Web programming

About cookies

A "cookie" is a small piece of information sent by a web server to store on the hard disk of a web browser client so it can later be read back from that browser client. This is useful for keeping specific information. An example is when a browser stores your passwords and user IDs. They are also used to store preferences of start pages.

A server, when returning an HTTP object to a client, may also send a piece of state information which the client will store. Included in that state object is a description of the range of URLs for which that state is valid. Any future HTTP requests made by the client which fall in that range will include a transmittal of the current value of the state object from the client back to the server. The state object is called a cookie.

This mechanism provides a tool which enables a host of types of applications to be written for web-based environments. Shopping applications can store information about the currently selected items, fee services can send back registration information and free the client from retyping a user-id on next connection, sites can store per-user preferences on the client and have the client supply those preferences every time the site is connected to. More specifically, uses are varied:

Online ordering systems
An online ordering system using cookies remembers what a person wants to buy even if the visit gets terminated.

Site personalization
This allows people to select an option, and from then on (until the cookie expires) the site guides them in viewing their chosen option.

Web site tracking
Site tracking can show you dead end paths, places in your website that people go to and get lost so to speak. It can also give you more accurate counts of how many people have been to pages on your site. You could differentiate 50 unique people seeing your site from one person hitting the reload button 50 times.

Targeted marketing
This is probably one of the main uses of cookies, they can be used to build up a profile of where you go, what adverts you click on and this information is then used to target adverts at you. Cookies can also be used to store which adverts have been displayed so the same advert does not get displayed twice.

User IDs
In Internet Explorer the first part of the cookie is your win95 log-in name. User IDs can also be remembered, such as IE5.0+ uses.

How cookies work

A command line in the HTML of a document tells the browser to set a cookie of a certain name or value. Here is an example of some script used to set a cookie. A cookie is introduced to the client by including a Set-Cookie header as part of an HTTP response, typically this will be generated by a CGI script.

Syntax of the Set-Cookie HTTP Response Header

This is the format a CGI script would use to add to the HTTP headers a new piece of data which is to be stored by the client for later retrieval.

Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. This is the only required attribute on the Set-Cookie header.
 
expires=DATE
The expires attribute specifies a date string that defines the valid life time of that cookie. Once the expiration date has been reached, the cookie will no longer be stored or given out.

The date string is formatted as:

Wdy, DD-Mon-YYYY HH:MM:SS GMT

This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, with the variations that the only legal time zone is GMT and the separators between the elements of the date must be dashes.

expires is an optional attribute. If not specified, the cookie will expire when the user's session ends.

 
domain=DOMAIN_NAME
When searching the cookie list for valid cookies, a comparison of the domain attributes of the cookie is made with the Internet domain name of the host from which the URL will be fetched. If there is a tail match, then the cookie will go through path matching to see if it should be sent. "Tail matching" means that domain attribute is matched against the tail of the fully qualified domain name of the host. A domain attribute of "me.com" would match host names "yes.me.com" as well as "yes.no.me.com".

Only hosts within the specified domain can set a cookie for a domain and domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL" and "INT". The default value of domain is the host name of the server which generated the cookie response.

 
path=PATH
The path attribute is used to specify the subset of URLs in a domain for which the cookie is valid. If a cookie has already passed domain matching, then the pathname component of the URL is compared with the path attribute, and if there is a match, the cookie is considered valid and is sent along with the URL request. The path "/" is the most general path. If the path is not specified, it as assumed to be the same path as the document being described by the header which contains the cookie.
 
secure
If a cookie is marked secure, it will only be transmitted if the communications channel with the host is a secure one. Currently this means that secure cookies will only be sent to HTTPS (HTTP over SSL) servers. If secure is not specified, a cookie is considered safe to be sent in the clear over unsecured channels.

Syntax of the Cookie HTTP Request Header

When requesting a URL from an HTTP server, the browser will match the URL against all cookies and if any of them match, a line containing the name/value pairs of all matching cookies will be included in the HTTP request.

Cookie: NAME1=OPAQUE_STRING1; NAME2=OPAQUE_STRING2 ...

Security

An HTTP Cookie cannot be used to get data from your hard drive, get your email address or steal sensitive information about your person. Early implementations of Java and JavaScript could allow people to do this but for the most part these security leaks have been plugged. But HTTP Cookie can be used to track where you travel over a particular site. This site tracking can be done without using cookies as well. You can disallow cookies with the latest browsers. Some database driven shopping sites and informational sites do need cookies to run.

Set cookies

The SetCookie function and the SetC functions are functions that define the cookie. They allow you to take user input from a form and convert it into 'cookie' format. This code is meant as an experimental base for you to work with.

1) Insert the following code in the section of the page.

then copy!

2) You then insert the form code for sending the data to the SetCookie and SetC functions. Experiment with onChange, onClick, onFocus, onBlur depending on whether you are using a button, text box, radio or button.

then copy!

TO VIEW THE RESULTS OF THE COOKIE

3) Paste into your page where you want the cookie results to be displayed. The GetCookieVal function and the GetCookie function find the cookies you created and display them on the page.

then copy!

 

How to pull the cookie value from the GetCookieVal and GetCookie functions:

then copy!

 

EXPLAINED

SetCookie: save to a cookie

function setCookie (name, value, expires) {
if (!expires) expires = new Date();
document.cookie = name + "=" + escape (value) + 
<-- save cookie value
"; expires=" + expires.toGMTString() +  "; path=/";
<-- set expiration date and path
}        
                                                

If you want to save someone's first name (such as Peter) to a cookie called "_fname", this is what you would need:

 var expdate = new Date ();
 expdate.setTime (expdate.getTime() + (1000 * 60 * 60 * 24 * 31));
 setCookie ("_fname", "Peter", expdate);

This function gives the cookie an expiration date of one month. The one month is set by multiplying 1000 milliseconds by 60 seconds by 60 minutes by 24 hours by 31 days. If you want to save the cookie for a year change the 31 to a 365. All cookies must have an expiration date. If you specify no expiration date the cookie will last through the current browser session. When setCookie() is run, it creates a cookie called "_fname", sets the value of the cookie to "Peter" and sets the expiration date to 31 days.

Another simple example:

function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : ";
expires=" + expires.toGMTString());
}

getCookie: read from a cookie

function getCookie (name) {
var acookie = document.cookie; 
var fname = name + "=";
var clen = acookie.length;
var cbegin = 0;
while (bbegin < clen) {
var bbegin = bbegin + fname.length;
if (acookie.substring(cbegin, bbegin) == fname) { 
var bend = acookie.indexOf (";", bbegin);
if (bend == -1) vend = clen;
return unescape(acookie.substring(bbegin, vend));
}
bbegin = acookie.indexOf(" ", bbegin) + 1;
if (bbegin == 0) break;
}
return null;
}

This function searches through the cookie until it finds the cookie name that you specify. Then it finds the value of the cookie and returns it. To get the cookie that was saved with "Peter's" name in it, you use:

document.write(getCookie("_fname"));

This prints out the value of the "_fname" cookie, which was set to "Peter". If you wanted to print out the value of some other cookie, you would just use its name instead of "_fname". You can give the value of a cookie to a variable, allowing you to manipulate the values and create programs that can save and load information. You always need to include both functions: setCookie() and getCookie().

Another example of getCookie:

function getCookie(name){
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
return null;
}

DelCookie: delete data from a cookie

If you wish to erase a cookie, use this function.

function delCookie (fname) {
var expireNow = new Date();
document.cookie = name + "=" +
"; expires=Wed, 03-Jan-90 00:00:01 GMT" +  "; path=/";
}

or more simple:

function delCookie(name) {
document.cookie = name + "=; expires=Wed, 03-Jan-90 00:00:01 GMT" + "; path=/";
}

Retrieve function

Function to retrieve an element's value from a form:

function getValue(element) {
var value = getCookie(element.name);
if (value != null) element.value = value;

Save function

Function to save an element's value from a form:

function setValue(element) {
setCookie(element.name, element.value, exp);
}

Example of a form

 

 


Last Page | Page 1 of 20 | Next Page
RadianT's blog offers informational items, such as tips and tricks on many computer related subjects.

Links

- Home
- Archives
- RSS Feed