Read and write cookies


Cookies are usefull in the world of web programming. You can save values on a site and read them on an other one. You can use cookies in JavaScript and it is pretty easy. All you need are two functions.
The first one is called "set_cookie" and creates them. In the call of the function you need give your cookie a name (make sure it is an unique name, or you overwrite some existing cookies). Then you need the value of the cookie. At least you give the cookie a 'lifetime'. An expiredate is important because there is no garbage collector for cookies.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function set_cookie(name,value,days) { 
 if (days) {
  var date = new Date();
  date.setTime(date.getTime()+(days*24*60*60*1000));
  var expires = "; expires="+date.toGMTString();
 }
  else expires = ""

  document.cookie = name+"="+value+expires+"; path=/";
}


Too read cookies you need the second function, called "read_cookie". For the call of this function you just need the name of the cookie. The function searches for your cookie and returns the value of it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function read_cookie(name) {
 var my_cookie_eq = name + "=";
 var ca = document.cookie.split(';');

 for(var i=0;i< ca.length;i++) {
  var c = ca[i];
  while (c.charAt(0)==' ') {
   c = c.substring(1,c.length);
  }
  if (c.indexOf(my_cookie_eq) == 0) {
   return c.substring(my_cookie_eq.length,c.length);
  }
 }
 return ""
}

Comments

Popular posts from this blog

How to support multiple languages in WPF