WebDevelopersJournal.comTips on Web Page Design, HTML and Graphics
SITE SEARCH
Newsletters
HTML (M-F) Text (M,TH)



Jobs at webdeveloper.com

Resources By Subject
Technical
Graphical
Authoring
Business
WDJ resources
Archive

internet.com

internet.commerce


Developer Channel


Find a web host with:
CGI Access DB Support Telnet Access
NT Servers UNIX Servers



Semi-automatic?

JavaScript
JavaScript Helper:
Meet Paige Turner, the least geeky geek we've ever come across.

Variables and Operators Explained:
First of a three part guide to JavaScript basics.

Controlling Forms:
Enhance your HTML forms with a touch of JS.

DHTML:
Forget how it works, let's see some in action!


Cookie D'Oh

by Gary Lee

If there is anything more introductory than a primer, this is it for cookies.

Cookies are not really a good subject for an article, because they are rather simple. Even the Netscape preliminary specification and the RFC are relatively short.
September 25, 1997

Cookie sites are filled with personal observations, puns, and assorted other filler just to make up for the fact that there really isn't much to say about it. Sort of like this opening paragraph.

For those of you who can glean more information from a code snippet than from the endless droning by writers trying to fill up space, here is a simple perl CGI script:


#!/usr/bin/perl



if ($cookie = $ENV{HTTP_COOKIE}) {

    print "Content-type: text/html\n\n";

    print "<PRE>$cookie</PRE><P>";

}

else {

    print "Set-Cookie: DoesThisWork=\"yes\"; Version=\"1\"\n";

    print "Cache-control: no-cache=\"set-cookie\"\n";

    print "Content-type: text/html\n\n";

    print "<PRE>The cookie has not been previously set.</PRE><P>"

}

Try it out. The first time you load it, it should tell you The cookie has not been previously set. The next time, if you are using a browser that handles cookies, it will say something like DoesThisWork="yes".

This covers the basics of cookies. Cookies are just a string that your browser stores somewhere. The most exotic thing you could store with a cookie might be the colour of your underwear. It is what you do with the information that might make cookies useful.

Anyway, back to the script. It is divided into two sections: reading a cookie and writing a cookie. Reading a cookie is simple enough...it is stored in the environment variable HTTP_COOKIE. It will look like a NAME=VALUE pair, much like something you would get from an HTML form. Once you get the string, you can manipulate it to do anything you wish, from keeping track of a reader's preferences or the contents of a shopping cart to those You have been here X times (which are the cookie equivalent of using an animated gif for those useless Under Construction images or javascript for the ubiquitous status bar messages).

The second part of the script involved in writing a cookie is simpler. Before the Content-type header that preceeds any HTML output, place a Set-Cookie header. The above script contains the two required attributes as specified in RFC 2109:

  • a NAME=VALUE pair containing the name of the cookie and its value
  • a Version=version pair identifying which specification the cookie is using.

The attributes are separated by semi-colons. Semi-colons would also separate any of the optional attributes.

You might be wondering about the other header before the Content-type. It is a Cache-control header that stops caching of the set-cookie header. Why? I quote from RFC 2109 because I'm lazy:

If the cookie is intended for use by a single user, the Set-cookie header should not be cached. A Set-cookie header that is intended to be shared by multiple users may be cached.

Ok. The reason why I do it is because it's neat. (And the fact that I think it is neat partially explains the state of my personal life.) If you don't like it, don't do it. It's like cooking...start with a basic recipe but don't go crazy trying to follow it. Add things in, take things out, and have fun. The worst you can do is give everyone food poisoning.

What happens if you can't use CGI? Why, you can use Javascript, silly.

Here is one of those "You have been here times" things. You need a Javascript-enabled browser to see it working properly. Reload a couple of times and you should see the number go up.

If you view the HTML source, you can see the Javascript function in the HEAD, the function call in the BODY, and the name I give to the FORM. Just your average Javascript gimmick. Here is the function itself:


function doCookie() {

   if (-document.cookie.length < -4) {

      var oldck = document.cookie.substring(4,document.cookie.length);

   }

   else {

      var oldck = 0;

   }

   document.cktest.cookievalue.value = oldck;

   var intck = parseInt(oldck);

   var ck = intck + 1;

   document.cookie = "num=" + ck;

}

You might realize from the snippet that the NAME=VALUE pair is stored in property document.cookie. The cookie I want is in the form num=X. I check to see if the cookie length is greater than 4. If it is, that means the cookie has been previously set, and I use substring to extract the fourth to last characters in the string, thereby skipping the num= part and leaving me only the X.

After reviewing the site with lynx, I changed the script to check if "-length < -4" instead of "length > 4". The ">" ends the comment I use to hide the JavaScript from lynx users, resulting in a lot of messy code displaying on the screen.

So, all that math you learn is really useful. Stay in school!

If the cookie length is less than 4, it means there is no num=X, and I haven't previously created the cookie. So I start off the count with 0.

Then I make the value of the form text field equal to X, convert it into an integer, add one to it, and set the document.cookie. Easy as pie, especially if you don't read this and simply cut-and-paste the function.

And that is it. You can now call yourself a cookie programmer (or perhaps an HTTP State Management Mechanism programmer), because you are. It is up to you to decide whether to use your new skill for good or evil. While you trying to decide, I'll send you a cookie with my underwear colour...

Gary Lee
is a co-owner of meep! media inc., an Internet and Intranet consulting company. He is also one of the programmers, and creator of meep! media's first product, meep!Board, a message board system. Gary is the Editor of Web Tech, one of meep! media's online publications.
Suits PonytailsPropheadsContact WDJDiscussWeb AudioSearch