Using Cookies 
A cookie is a little string stored on the users computer. They are quite easy to use via Javascript. The functions below works with Microsoft Internet Explorer 3+ and Netscape Navigator 2+. Note: Cookies do not work on local web-pages. They must reside on a webserver.
Creating a Cookie
The script below will create your cookie:
<script language=javascript type="text/javascript">
<!--
function SetCookie(name, value, expires, path, domain, secure)
{ document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
// -->
</script>
A cookie has a Name, Value and Expire Date. The Name and Value are strings and must be enclosed like 'MyCookie' and 'MyValue'. The Expire Date can be specified in three ways:
- Cookie expires at the end of the user's browser session
SetCookie( Name, Value );.
- Cookie expires n milliseconds in the future.
var expiration = new Date();
expiration.setTime(expiration.getTime() + n);
SetCookie( Name, Value, expiration);
- Cookie expires at a certain date/time in the future. The date/time must be specified like this:
Month: 1-12,
Date: 1-31,
Year: 1970-20xx,
Hour: 0-23,
Minutes: 0-59,
Seconds: 0-59.
var expiration = new Date();
expiration.setMonth( Month );
expiration.setDate( Date );
expiration.setYear( Year );
expiration.setHours( Hour );
expiration.setMinutes( Minutes );
expiration.setSeconds( Seconds );
SetCookie( Name, Value, expiration);
Retrieving a Cookie's Value
The function below is very simple to use, just call GetCookie( Name );
Note: This function can only read cookies created from the same subdirectory on the server. If you create a cookie from http://myserver/mypath/index.php3, you can only read the cookie from documents in http://myserver/mypath. If you want to read from another directory or host, see Netscapes javascript reference.
<script language=javascript type="text/javascript">
<!--
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;
}
// -->
</script>
Deleting a Cookie
The script below can delete your cookie. Just call DelCookie( Name );
<script language=javascript type="text/javascript">
<!--
function DelCookie (name,path,domain)
{ if (getCookie(name))
{ document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
// -->
</script>
|