Cookies review

JavaScript cookies allow programmers to store limited amounts of state information on a user's hard drive. Surprisingly, however, cookies pose almost no security threat to the end user.

Included in these examples are two functions - the setCookie() function, and the getCookie() function - for working with cookies. The setCookie() function is responsible for creating and updating cookie values. It takes two arguments - the name of the cookie and the value to be assigned to it.

The getCookie() function is used to retrieve cookie values. The getCookie() function is sent one argument: the name of the cookie for which to search. If the cookie is found, its value will be returned. If it is not found, the cookie will return null.

The syntax for the two cookies looks like this:

setCookie("CookieName", "Cookie value");

tempVar = getCookie(cookieName);

To use the two cookie functions, include the following code in the head portion of your HTML documents. The two functions are explained in detail in the first example, so be sure to have a look.

// setCookie function
function setCookie(name, value)
{
var expires=new Date();
expires.setYear(expires.getYear() + 1);

var cookieString = name + "=" + escape(value) + "; expires=";
cookieString += expires.toGMTString();

document.cookie = cookieString;
}

// getCookie function
function getCookie(name)
{
cookieString = document.cookie;

for(i=0; i<cookieString.length;)
	{
	if(cookieString.substring(i, i + name.length) == name)
		{
		i += (name.length + 1);
		if(cookieString.indexOf(";", i) < i)
			return unescape(cookieString.substring(i, cookieString.length));
		else
			return unescape(cookieString.substring(i, cookieString.indexOf(";", i)));
		}
	i = cookieString.indexOf(";", i);
	if(i<0)
		return null;
	else
		i += 2;
	}

// This line of code should never execute!
return null;
}