|
Cookie Basics with ASP |
|
|
What is a cookie? According to Marie Callender's restaurants, it's a "bakery treat", which leads to the conundrum, "Why isn't called a Bakie then? You bake it after all, not cook it, right?" That's another whole topic though, better left to Cooking Today than ASP Today. But seriously, in the web-programming world, a cookie is simply a text file that is placed on a visitor's computer when they visit a website; storing information that is then is later retrieved for use by the website. Although that doesn't really sound very impressive, you can do some very useful things with cookies. For example, you can make a questionnaire on your website that asks the visitor what their favourite colours and fonts are and then customize the whole look and feel of the website just for them. You can also store passwords so visitors don't have to log in every time they visit. Cookies do have a few drawbacks. First, because certain unsavoury elements of the programming community have been known to do nasty things with cookies, most browsers have security settings that can be set so people don't have to accept cookies, so there's no guarantee that you'll be able to use them. Also, your visitor can intentionally (or more likely unintentionally) delete the cookie. If the visitor's computer ever gets a Blue Screen of Death, and has to reformat and reinstall everything, your cookie is gone. Lastly, some legacy browsers can't handle them, though, admittedly, it's pretty rare that you run into a browser that can't handle them. What Can You Do With Cookies?There are really only two basic things to do with cookies:
The basic syntax for sending a cookie is:Response.Cookies("CookieName")=value
So the following code would create a cookie on the visitor's computer named Response.Cookies("VisitorName")="Ken"
Or the following example would create the cookie on the visitor's computer
with the value in the variable Response.Cookies("VisitorName")=Request.Form("UserName")
The basic syntax for retrieving a cookie is:Request.Cookies("CookieName")
The request is basically treated like a variable. The following code is
requesting the cookie MyVar=Request.Cookies("KensCookie")
And the following code checks the cookie If Request.Cookies("KensCookie")="Yes" then
Deluxe Cookies(you know, the ones with macadamia nuts and white chocolate) You can also expand the code to include a Response.Cookies("VisitorName")("FirstName")="Ken"
Response.Cookies("VisitorName")("LastName")="Baumbach"
Two last things we need to discuss before we get into a real world example: Naming Conventions and Expiration . Naming ConventionsLike any variable, it is important to give your cookies unique names to keep track of them properly. You can also use one or both of the following properties to help with any possible security issues (but they take more lines of code): The Domain Property The Domain property tells where the cookie came from and limits it to be read from that domain, exclusively from that domain, which adds quite a bit of security. By default, the cookie is set to the domain in which it was created, but you can alter it for your needs. The code is as follows: Response.Cookies("CookieName").Domain = "www.mydomain.com"
The Path property The Path property adds even more security by allowing you to set the exact path on the domain where the cookie can be used. The following is an example: Response.Cookies("CookieName").Path = "/maindir/subdir/path"
ExpirationNormally, a cookie will expire and disappear after the browser has been closed. In many cases, such as our website personalization example below, we want to be able to store our cookies on the visitor's computer for longer than that. Luckily, we have a way to do that. The following code sets the expiration date of the cookie to January 1, 2010: Response.Cookies("CookieName").Expires=#January 01, 2010#
And the following code sets the cookie expiration date to 365 days after the cookie was created: Response.Cookies("CookieName")=Date+365
Cookies in the Real World…mmmm…Mighty TastyLet's start with a really easy real world example. Let's say you have a survey that you want everyone stopping by your website for the first time to fill out, but you don't want to annoy them by going to the survey every time they stop by. Cookies are an excellent way to take care of this problem without worrying about dealing with a database. <%@ LANGUAGE="VBSCRIPT" %> <% Survey=Request.Cookies("KensSurvey")
If Survey ="" then Response.Cookies("KensSurvey")="x"
Response.Cookies("KensSurvey").Expires=#January 01, 2010#
Response.Redirect "survey.asp" Else 'rest of the page End if %> Okay, now let's take a look under the hood: First, we set-up the page and request the cookie as variable <%@ LANGUAGE="VBSCRIPT" %> <% Survey=Request.Cookies("KensSurvey")
Then we check to see if there is a cookie: If Survey ="" then If there isn't, then we create the cookie and set it so that it does not
expire for a while so they won't be sent to Response.Cookies("KensSurvey")="x"
Response.Cookies("KensSurvey").Expires=#January 01, 2010#
Response.Redirect "survey.asp" If the cookie was already there, then we send our visitor to the rest of the regular page instead: Else 'rest of the page End if %> Example 2Here is another simple example. Let us say that you want to greet the visitor by first name whenever they visit. <%@ LANGUAGE="VBSCRIPT" %> <% RequestName = Request.Form("Name")
RequestLeaveMeAlone = Request.Form("LeaveMeAlone")
If RequestName <>"" or RequestLeaveMeAlone <>"" then Response.Cookies("MySiteVisitorName") = RequestName
Response.Cookies("MySiteVisitorName").Expires = #January 01, 2010#
Response.Cookies("MySiteLeaveMeAlone") = RequestLeaveMeAlone
Response.Cookies("MySiteLeaveMeAlone").Expires = #January 01, 2010#
End if VisitorName = request.cookies("MySiteVisitorName")
LeaveMeAlone = request.cookies("MySiteLeaveMeAlone")
If VisitorName ="" and LeaveMeAlone ="" then %> <HTML> <HEAD> </HEAD> <body bgcolor="#ccffff" text="black" link="navy" vlink="purple"> <DIV ALIGN="CENTER"> <form action="index.asp" method="POST"> <H2>Let's be friends</H2> What's your name (leave blank and hit the Submit button if you don't want us to know)? <input type="text" name="name"><BR><BR> <input type="hidden" name="LeaveMeAlone" value="x"> <input type="submit" value="Submit"> </FORM> </DIV> </BODY> <% End if If VisitorName <> "" then Response.write "Hi, " & VisitorName & "! I hope you are having a great day!" End if 'rest of the page %> Okay, let's see what's going on behind the scenes with this example. First, we set-up the page. Then we check for the form variables for the same-page Name Request form (see below). If the form variables exist, then we create cookies out of them and set the expirations: <%@ LANGUAGE="VBSCRIPT" %> <% RequestName = Request.Form("Name")
RequestLeaveMeAlone = Request.Form("LeaveMeAlone")
If RequestName <>"" or RequestLeaveMeAlone <>"" then Response.Cookies("MySiteVisitorName") = RequestName
Response.Cookies("MySiteVisitorName").Expires = #January 01, 2010#
Response.Cookies("MySiteLeaveMeAlone") = RequestLeaveMeAlone
Response.Cookies("MySiteLeaveMeAlone").Expires = #January 01, 2010#
End if Next, we request the cookies: VisitorName = request.cookies("MySiteVisitorName")
LeaveMeAlone = request.cookies("MySiteLeaveMeAlone")
If the cookies don't exist on the visitor's computer, then we create a form to ask for the information: If VisitorName ="" and LeaveMeAlone ="" then %> <HTML> <HEAD> </HEAD> <body bgcolor="#ccffff" text="black" link="navy" vlink="purple"> <DIV ALIGN="CENTER"> <form action="index.asp" method="POST"> <H2>Let's be friends</H2> What's your name (leave blank and hit the Submit button if you don't want us to know)? <input type="text" name="name"><br><br> <input type="hidden" name="LeaveMeAlone" value="x"> <input type="submit" value="Submit"> </FORM> </DIV> </BODY> <% End if Otherwise, we give our visitor a nice greeting, but only if they gave us their name, and display the rest of the page: If VisitorName <> "" then Response.write "Hi, " & VisitorName & "! I hope you are having a great day!" End if 'rest of the page %> While this example may be simplistic, it has many possibilities for creative expansion. You could add a great deal of functionality to your form, so as to allow for customisation of your website. You could have your visitors customize font style and colour, background colour and any number of other website themes. You could ask for your visitor's birthday and put a script that displays "Happy Birthday!" if they visit your website on that day. As you can see, the possibilities with cookies are endless and this article only scratches the surface. ASPToday has several other useful articles on the subject, so go out there and get cooking (or is that baking?)!!!
|