The Lowdown
Cookies can be useful at times, and its really simple once you understand the basics!
The thing to remember is, when you want to SET a cookie, always use RESPONSE.cookies (I capitalized response for emphasis - its not case sensitive)... when you want to GET info from a cookie, you'll want to use REQUEST.cookies... That being said, let's say you want to set a real simple cookie, let's use UserID as an example. So... to set the cookie (again, keeping this very simple), we'll do something like this:
response.cookies("UserID")="Kathi"
Remember that strings must be enclosed in double quotes. If that had been a numeric value, no quotes would have been needed.
Another very important note is that you should put <% response.buffer=true %> at
the very start of the script (the first line on the page to avoid an error. Cookie information is carried in the http headers, and
if those headers have already been written, you'll see a nice little error message informing you
of that fact.
Now, let's say you want to retrieve that cookie from another page and write it out to the browser. All you'd have to do is:
response.write request.cookies("UserID")
Die, Cookie, Die ;)
Another thing to remember is that if you don't set an expiration date for the cookie, it "dies" when the browser is closed, so if you want it to persist on the user's system, you will need to set an expiration date like this:
response.cookies("UserID").Expires=DateAdd("d",30,Date)
In the above example, I set it to expire in 30 days using the DateAdd function - the "d" is for days. "m" can be used here for month, "y" for year... the number is the number of units (be it days, months or years), and Date just fills in today's date...
Let's say you have a cookie you want to die immediately, you could do the following:
response.cookies("UserID").Expires=DateAdd("d",-1,Date)
This sets the expiration to yesterday, which in effect kills the cookie and removes it from the user's system immediately.
Using Keys
You can also use "keys" in your cookies. For example, I have an application where I track a user's first name (fname), last name (lname), and User ID (UID). Rather than set these all individually, I just set them all as part of a single cookie, using "user" as a key:
response.cookies("user")("fname")="Kathi"
response.cookies("user")("lname")="O'Shea"
response.cookies("user")("UID")="kathio"
This way you can store a lot of information in one cookie, and iterate through the values if needed:
For each item in request.cookies("user")
response.write item & ": " & request.cookies(item) & "
"
Next
The above for...next would send a list to the browser like this:
fname: Kathi
lname: O'Shea
UID: kathio
Check It Out!
So far, so good. Now, let's run through an example:
Test this snippet by entering your first name in the
text box, and hit submit.
The page will submit to itself.