Tuesday, December 14, 2010

What are cookies?


What are cookies?

Cookies are small amounts of data stored by the web browser. They allow you to store particular information about a user and retrieve it every time they visit your pages. Each user has their own unique set of cookies.
Cookies are typically used by web servers to perform functions such as tracking your visits to websites, enabling you to log in to sites, and storing your shopping cart. However we don't need fancy web server programming to use cookies. We can use them in JavaScript, too!

The document.cookie property

Cookies in JavaScript are accessed using the cookie property of the document object. In simple terms, we create a cookie like this:

document.cookie = "name=value; expires=date; path=path;
domain=domain; secure";
...and retrieve all our previously set cookies like this:

var x = document.cookie;
Let's look more closely at how to set and retrieve cookies.

Setting a cookie

To set a cookie, we set the document.cookie property to a string containing the properties of the cookie that we want to create:

document.cookie = "name=value; expires=date; path=path;
domain=domain; secure";
These properties are explained in the table below:
PropertyDescriptionExample
name=valueThis sets both the cookie's name and its value.username=matt
expires=dateThis optional value sets the date that the cookie will expire on. The date should be in the format returned by the toGMTString()method of the Date object. If the expiresvalue is not given, the cookie will be destroyed the moment the browser is closed.expires=
13/06/2003 00:00:00
path=pathThis optional value specifies a path within the site to which the cookie applies. Only documents in this path will be able to retrieve the cookie. Usually this is left blank, meaning that only the path that set the cookie can retrieve it.path=/tutorials/
domain=domainThis optional value specifies a domain within which the cookie applies. Only websites in this domain will be able to retrieve the cookie. Usually this is left blank, meaning that only the domain that set the cookie can retrieve it.domain=elated.com
secureThis optional flag indicates that the browser should use SSL when sending the cookie to the server. This flag is rarely used.secure
Let's look at a few examples of cookie setting:

document.cookie = "username=John;
expires=15/02/2003 00:00:00";
This code sets a cookie called username, with a value of "John", that expires on Feb 15th, 2003 (note the European time format!).


var cookie_date = new Date ( 2003, 01, 15 );
document.cookie = "username=John;
expires=" + cookie_date.toGMTString();
This code does exactly the same thing as the previous example, but specifies the date using the Date.toGMTString() method instead. Note that months in the Date object start from zero, so February is 01.


document.cookie = "logged_in=yes";
This code sets a cookie called logged_in, with a value of "yes". As the expires attribute has not been set, the cookie will expire when the browser is closed down.


var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = "logged_in=;
expires=" + cookie_date.toGMTString();
This code sets the logged_in cookie to have an expiry date one second before the current time - this instantly expires the cookie. A handy way to delete cookies!

There's no escape!

Strictly speaking, we should be escaping our cookie values -- encoding non-alphanumeric characters such as spaces and semicolons. This is to ensure that our browser can interpret the values properly. Fortunately this is easy to do with JavaScript's escape() function. For example:

document.cookie = "username=" + escape("John Smith")
+ "; expires=15/02/2003 00:00:00";

A function to set a cookie

Setting cookies will be a lot easier if we can write a simple function to do stuff like escape the cookie values and build the document.cookie string. Here's one we prepared earlier!

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
var cookie_string = name + "=" + escape ( value );

if ( exp_y )
{
var expires = new Date ( exp_y, exp_m, exp_d );
cookie_string += "; expires=" + expires.toGMTString();
}

if ( path )
cookie_string += "; path=" + escape ( path );

if ( domain )
cookie_string += "; domain=" + escape ( domain );

if ( secure )
cookie_string += "; secure";

document.cookie = cookie_string;
}
This function expects the cookie data to be passed to it as arguments; it then builds the appropriate cookie string and sets the cookie.
For example, to use this function to set a cookie with no expiry date:

set_cookie ( "username", "John Smith" );
To set a cookie with an expiry date of 15 Feb 2003:

set_cookie ( "username", "John Smith", 2003, 01, 15 );
To set a secure cookie with an expiry date and a domain of elated.com, but no path:

set_cookie ( "username", "John Smith", 2003, 01, 15, "",
"elated.com", "secure" );
Feel free to use this function in your own scripts! :)

A function to delete a cookie

Another useful cookie-handling function is provided below. This function will "delete" the supplied cookie from the browser by setting the cookie's expiry date to one second in the past.

function delete_cookie ( cookie_name )
{
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
To use this function, just pass in the name of the cookie you would like to delete - for example:

delete_cookie ( "username" );
Again, you can use this function in your own scripts if you like. :)

Retrieving cookies

To retrieve all previously set cookies for the current document, you again use thedocument.cookie property:

var x = document.cookie;
This returns a string comprising a list of name/value pairs, separated by semi-colons, for all the cookies that are valid for the current document. For example:

"username=John; password=abc123"
In this example, 2 cookies have been previously set: username, with a value of "John", andpassword, with a value of "abc123".

A function to retrieve a cookie

Usually we only want to read the value of one cookie at a time, so a string containing all our cookies is not that helpful! So here's another useful function that parses thedocument.cookies string, and returns just the cookie we're interested in:

function get_cookie ( cookie_name )
{
var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

if ( results )
return ( unescape ( results[2] ) );
else
return null;
}
The function uses a regular expression to find the cookie name and value we're interested in, then returns the value portion of the match, passing it through the unescape() function to convert any escaped characters back to normal. (If it doesn't find the cookie, it returns a null value.)
Using the function is easy. For example, to retrieve the value of the username cookie:

var x = get_cookie ( "username" );
Again, feel free to use this function with your own JavaScript code!

A simple example

In this example, we've created a page that prompts you for your name the first time you visit it, then stores your name in a cookie and displays your name in the page on subsequent visits.
Open the page in a new window. The first time you visit the page, it should ask you for your name and store it in a cookie. If you visit the page again at any point, it will get your name from the cookie and display it within the page.
Try closing the window that pops up, then opening it again in a new window. Notice that this time it still displays the user name that it retrieved from the cookie!
The cookie is given an expiry date of 1 year from the current date, which means that the browser will remember your name even if you close it down and re-open it.
You can clear the cookie by clicking on the Forget about me! link, which calls ourdelete_cookie() function and then refreshes the page to prompt you for a name again.
You can view all the JavaScript source for the example page by switching to the other browser window now and using the View Source option in your browser. Here's the main part of the code:

if ( ! get_cookie ( "username" ) )
{
var username = prompt ( "Please enter your name", "" );

if ( username )
{
var current_date = new Date;
var cookie_year = current_date.getFullYear ( ) + 1;
var cookie_month = current_date.getMonth ( );
var cookie_day = current_date.getDate ( );
set_cookie ( "username", username, cookie_year, cookie_month, cookie_day );
}
}
else
{
var username = get_cookie ( "username" );
document.write ( "Hi " + username + ", welcome to my website!" );
document.write ( "

Forget about me!
" );
}
Notice how the function uses our get_cookie()set_cookie() and delete_cookie()library functions to do the hard work!

No comments:

Post a Comment