Cookies

By habesh

A Cookie is a small amount of named data stored by the web browser and associated with a particular web page.

Things to watch for while implementing cookies.

  • A total of 20 cookies per site or domain with a total max size of 4KB.
  • A user could disable cookies in their browsers(although session cookies may still be enabled). You may want to first check that they are enabled before trying to store persistent cookies.
  • Cookies default visibility is for all pages in the same directory as the page that created it and sub-directories of that directory. This could be changed by setting the cookie ‘path’ attribute.
  • Cookies are accessible only to pages on the same domain.
  • Cookies are stored on the client machine and are not shared by different browsers. eg. Cookies stored by IE is not visible to FF and vice verse.

Cookies are sent to the server on every HTTP request and could be manipulated both on server side using server side scripts and on client side using javascript. Below is a javascript methods to get, set and remove cookies

function set(name,value,day){
if(!name){
return;
}
var cookie;
var date = new Date();
cookie = name + “=” + encodeURIComponent(value);
if(typeof day === ‘number’){
date.setTime(date.getTime()+(day*24*60*60*1000));
cookie += “; expires=”+date.toGMTString();
//cookie += “; max-age=”+day*24*60*60;
}
cookie += “; path=/”;
document.cookie = cookie;
}

To set session cookie – set(“cookieName”, “cookieValue”);
To set persistent cookie(for 30 days) : set(“cookieName”, “cookieValue”, 30); function get(name){
if(!name || document.cookie.indexOf(name) === -1){
return;
}
var curCookie;
var list = document.cookie.split(“; “);
for(var c=0;c<list.length;c++){
curCookie = list[c];
if(curCookie.indexOf(name + “=”) != -1){
return decodeURIComponent(curCookie.subString(name.length+1, curCookie.length));
}
}
}

To get a cookie – get(“cookieName”);

function remove(name){
set(name,”",-1);
}

To remove a cookie – remove(“cookieName”);

You may have noticed a commented line in the above ’set’ function that sets the max-age attribute(a way to specify the life time of a cookie according to HTTP 1.1 spec) of a cookie, though that may not work in IE so we should use a depreciated ‘expires’ attribute.

Leave a Reply