Write Your First HTTP Cookie

Learn How to Write and Read an HTTP Cookie

Cookies are set by the browser, often with a CGI or JavaScript. You can write a script to set a cookie at any event on a Web page. For example, if you go to this page you will be given the option to set a cookie when you click another link. The cookie looks something like this:

Set-Cookie: Count=1; expires=Wednesday, 01-Aug-2040 08:00:00 GMT; path=/; domain=webdesign.about.com

This means:

  • Set-Cookie:
    This is the call that set's the cookie in the browser's cookie store.
  • Count=1;
    This is the name of your cookie.
  • expires=Wednesday, 01-Aug-2040 08:00:00 GMT;
    This details when the cookie will expire.
  • path=/;
    This is the minimum path that needs to exist for the cookie to be returned.
  • webdesign.about.com
    The domain that set the cookie, and is the only domain that can retrieve the cookie.

Write the Cookie with JavaScript

Use the following code to write your cookie:

<script language="JavaScript">
cookie_name = "Basic_Cookie";
function write_cookie() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
document.cookie=cookie_name+"=1; expires=Wednesday, 01-Aug-2040 08:00:00 GMT";
} else {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = eval(document.cookie.substring(countbegin, countend)) + 1;
document.cookie=cookie_name+"="+count+"; expires=Wednesday, 01-Aug-2040 08:00:00 GMT";
}
}
</script>

Read Your Cookie

Once you've written the cookie, you need to read it in order to use it. Use this script to read your cookie:

<script language="JavaScript">
function gettimes() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = document.cookie.substring(countbegin, countend);
if (count == 1) {
return (count+" time");
} else {
return (count+" times");
}
}
}
return ("0 times");
}
</script>

Call Your Cookie in a Link

Set your cookie when someone clicks a link with this code in your HTML body:

<script language="javascript">document.write(gettimes());</script>

Next page> Are Cookies Dangerous? > Page 1, 2, 3

Was this page helpful?