| << 8.1.1- Tracking Users | Chapter8 | 8.2.0- The Application Object >> |
Using Cookies
A web site might have had a thousand visitors, but for all the web site coordinator could know, every visit might have been made by the same visitor! Cookies were introduced as a method of identifying and marking each different visitor to a web site.
Cookies are text files written by the client browser, containing information sent by a server, which reside on the user's computer. They store information about the user, and are used by a particular server (or server within the same sub-domain) that the user has visited previously to personalize web pages, and determine where a user has been before within the same domain. They can then be used to keep users up to date with relevant information. Each web server, when a user accesses it, can send a cookie, which the user must accept if the server is to read the cookie on the user's machine during future visits. If the user doesn't accept the cookie, it can't be read by the server in future.
There are all sorts of cookie myths on the Internet. Mostly they revolve around the notion that a smart programmer can get unauthorized information from a user, violating the user's " right to privacy". Let's set the record straight. A cookie can only store information, which the user sends voluntarily or selects on a page and that can only happen if the "accept cookies" option in the browser is turned on by the user. No one can get your e-mail address or your home address if you don't voluntarily send the information by filling and submitting a form.
Individual cookies on Netscape are limited to 4kb of data. On IE5 the theoretical size is unlimited. The maximum number of cookies is also browser specific and once this limit is reached, the oldest cookie will be deleted to make room for the newest one. So make sure you use cookies judiciously.
The Cookies Collection
We mentioned in the last chapter that the Request object had a Cookies collection – it's now time to talk about this collection. The Cookies collection holds information from all the cookies set by any one application. That is, when a client establishes a session with the server the values that the server reads from the client's cache of cookies are held in the Cookies collection. This means that they are available for easy access by the server.
Unlike the Form and Querystring collections, the Cookies collection does not have a Count property but, like the Form collection, it can hold multiple values for the same cookie name. When this happens, the cookie is said to have keys, and each key holds a separate value.
Domains and servers can only read cookies that they themselves have set. If server X writes a cookie, then server Y cannot read it. If domain http://Myapp sets a cookie, then domain http://MyApp2 cannot read the cookies set by MyApp, and vice versa, unless the second domain is a sub domain of the first. When demanded by the server, the cookie that comes with the request is read-only. You can set the value for a cookie using the Response object, which you will learn about later in this chapter.
The general syntax for retrieving cookies is:
Request.Cookies("cookie")[("key")].attribute
So display the contents of a cookie in your web page you could use:
Response.Write Request.Cookies("cookie")
Creating Cookies with the Response Object
As well as reading information supplied by a client's cookies, the server needs to be able to write information to cookies on the client's machine. ASP uses the Response object's features to set cookies' values.
Until ASP was released, the most common way to set cookies was using CGI or in client-side JavaScript. The syntax for doing this with JavaScript is fairly complex – even daunting – if you're not over-familiar with JavaScript. ASP (with VBScript) provides a one-line instruction method to set and retrieve cookies.
The syntax for writing cookies in ASP is:
<% Response.Cookies("cookie") = value %>
If value is a string, it must be enclosed in quotes.
If you use this method to set a cookie, the following HTTP header is generated:
Set-Cookie:YOURCOOKIENAME=somevalue
You can see that the Response.Cookies method is simply a way of sending the Set-Cookie HTTP header without resorting to complicated code. Therefore you should use Response.Cookies before you write any data in the response body.
Using Keys
If you add a key value, then you can access this cookie like a collection. This means that one cookie can have multiple values stored with it.
<% Response.Cookies("cookie")("key") = value %>
If a cookie is used to store more than one value we have to specify which of these multiple values we want to set. To do this, we refer to it via its key value. The key value is similar to a variable name. The general syntax for writing cookies with keys is:
Response.Cookies("thesameCookieName")("somekey") = "SomeValue"
Response.Cookies("thesameCookieName")("anotherkey") = "AnotherValue"
If you issue another cookie with the same name but without specifying the key, you will overwrite all cookie values for that cookie's name.
The HasKeys Property
ASP uses the HasKeys property to determine whether or not a cookie holds multiple values. To check if a cookie holds multiple values, we interrogate the HasKeys property:
Request.Cookies("theCookie").HasKeys
If the cookie theCookie has keys, this statement returns True, otherwise it returns False. To iterate through the individual values for cookies with keys, use this model script:
For Each Cookie in Request.Cookies
If Request.Cookies(Cookie).HasKeys Then
For Each CookieKey in Request.Cookies(Cookie)
Response.Write(Cookie) & " ."
Response.Write(CookieKey) & " ="
Response.Write(Request.Cookies(Cookie)(CookieKey))
Next
Else
Response.Write(Cookie) & " ="
Response.Write(Request.Cookies(Cookie)) & " <BR>"
End If
Next
Making your Cookie Persist
A cookie set with the basic syntax will persist for as long as the browser is open, or until the session expires. As soon as the browser is closed, the cookie's value will disappear.
To make a cookie persist, i.e., for the cookie to be written to the client browser's hard disk (the "cookie jar"), you have to set an expiration date for the cookie. The general syntax for doing this is:
Response.Cookies("Cook").Expires = "July 4, 2001"
A Better Way to Set a Cookie's Expiration Date
Though setting the cookie's expiration date as " July 4, 2001" works, a better way to set the expiration date is to use relative date values. This is also better when the client and server are in different time zones. Since Date is a built-in VBScript function, you could set the expiration date as Date + X, where X stands for the number of days you want the cookie to "live":
Response.Cookies("Cook").Expires = Date + 1
This will set the expiration date to 1 day from today.
Deleting a Cookie
To delete a cookie, set its Expires property to any date prior to today. The easiest way to do this is to use relative date values, as shown in this example:
Response.Cookies("Cook").Expires = Date - 1
Again, this technique could fail due to different time settings on server and client, so maybe something like Date – 1000 would be more secure.
Try It Out – Using Cookies in ASP
There are many sites on the web that will ask you to register in order to get some level of enhanced access. Once you have registered, you are given a user name and password. The next time you visit the site, you are asked to enter these before being granted access. Some sites will give you the option of saving your username and password as a cookie, so that you will automatically be logged in next time you visit. In this example, we will look at how to do this.
Open your favorite HTML editor, and create the following file:
<HTML>
<HEAD>
<TITLE>Cookie Test - Login</TITLE>
</HEAD>
<BODY>
Please enter your e-mail address and password to login to the system.
<FORM ACTION = "CheckLogin.asp" METHOD="POST" >
E-Mail Address: <INPUT TYPE = "Text" NAME = "Email" SIZE = "40"><BR>
Password: <INPUT TYPE = "Password" NAME = "Password" SIZE = "10"><P>
<INPUT TYPE = "Checkbox" NAME = "SaveLogin"> Save Login as a Cookie?<P>
<INPUT TYPE = "Submit" VALUE = "Login">
<INPUT TYPE = "RESET">
</FORM>
</BODY>
</HTML>
The Password type of input box hides values that are typed in by displaying asterisks instead of the actual character that was typed. You will probably be familiar with this from when you login to Windows when you start up your machine. You can find more details about password boxes in Appendix F.
Save the file as login.asp in a virtual directory of your web server.
Create another new file, and enter the following:
<%
Dim bLoginSaved
If Request.Form("SaveLogin") = "on" Then
Response.Cookies("SavedLogin")("EMail") = Request.Form("email")
Response.Cookies("SavedLogin")("pw") = Request.Form("password")
Response.Cookies("SavedLogin").Expires = Date + 30
bLoginSaved = True
Else
bLoginSaved = False
End If
%>
<HTML>
<HEAD>
<TITLE>Cookie Test - Check Login</TITLE>
</HEAD>
<BODY>
<%
If bLoginSaved Then
Response.Write "Saving Login information to a cookie<HR>"
End If
%>
Thank you for logging into the system.<P>
E-Mail address confirmation: <%= Request.Form("email")%>
</BODY>
</HTML>
Save the file as checkLogin.asp in the same directory.
Load the login.asp page into your browser.
|
|
Enter an e-mail address and password. You should also check the Save Login as a Cookie button to save your login. The press the Login button. Note: we will not be validating the e-mail and password against anything, so feel free to enter whatever you want.
|
|
How It Works
In this example, we are using two ASP files. The first one will display the login screen for the user. They are asked to enter their e-mail address and password. They can also click on a checkbox that will have their login information saved as a cookie.
If you look at the code for login.asp, you will see no Active Server Pages code. So you may be wondering why this file is an .asp and not an .htm. In the next example, we will be adding some server-side script to this file, so we thought ahead and gave it the .asp name. Once the form is submitted, the checkLogin.asp page will handle the results.
<%
Dim bLoginSaved
If Request.Form("SaveLogin") = "on" Then
When the form information is passed to the checkLogin.asp page, the first thing that we want to do is see if the user has requested that their login information be saved in a cookie. We are declaring a variable called bLoginSaved. This boolean variable will be set to true if the user wants a cookie set. It will be false if they do not. This will allow us to display a notification later in the page.
Response.Cookies("SavedLogin")("EMail") = Request.Form("email")
Response.Cookies("SavedLogin")("pw") = Request.Form("password")
Response.Cookies("SavedLogin").Expires = Date + 30
bLoginSaved = True
The name of the cookie we are creating is SavedLogin. It will contain two keys of information. These keys will hold the e-mail address and password of the user. The values for these keys will come from the Form collection of the Request object. The information that the user entered in the fields on the login.asp page will be stored in this collection.
We will be setting this cookie to expire 30 days from today. As you saw earlier, you can use the VBScript Date function to determine the current date, and then add the desired lifetime of the cookie in days to that value. The last step is to set the flag that we declared earlier to true. This is to indicate that a cookie has been set for the user. If the user hasn't set this checkbox, then they didn't want the cookie saving so we set the Boolean variable to false to ensure we don't save the information as a cookie.
Else
bLoginSaved = False
End If
%>
In the case where the user did not request that a cookie be set, we will set the flag to false. We have now reached the end of our ASP script block, so we terminate it with the %> statement. Now that we have done all of the cookie processing, we can turn to what the user sees.
<BODY>
<%
If bLoginSaved Then
Response.Write "Saving Login information to a cookie<HR>"
End If
%>
Thank you for logging into the system.<P>
First, we want to inform the user that a cookie was saved to their machine. Since we set a boolean flag earlier in the page, we can check its value. If it is set to true, then we will display a message for the user. If not, then we will just go on displaying the rest of the page.
E-Mail address confirmation: <%= Request.Form("email")%>
</BODY>
</HTML>
Finally, we want to display the user's e-mail address that was just entered. This is done primarily as a validation that the correct information was entered. To display the e-mail address, we will retrieve it from the Form collection of the Request object.
Now that we have seen how to set the cookies, let's take a look at another example that will show how we can use the cookies in our login page.
Try It Out – Using Cookies in ASP Part 2
In this example, we will modify the two ASP scripts from the previous example so that the login page will check for the existence of a cookie. The login check page will inform the user if their login was entered via a cookie, or by direct input.
1. Using your favorite HTML editor, open the login.asp file and make the following changes.
<%
If Request.Cookies("SavedLogin").HasKeys then
Response.Redirect ("CheckLogin.asp?cookie=1")
End If
%>
<HTML>
<HEAD>
<TITLE>Cookie Test - Login</TITLE>
</HEAD>
<BODY>
Please enter your e-mail address and password to login to the system.
<FORM ACTION = "CheckLogin.asp" METHOD="POST">
E-Mail Address: <INPUT TYPE = "Text" NAME = "Email" SIZE = "40"><BR>
Password: <INPUT TYPE = "Password" NAME = "Password" SIZE = "40"><P>
<INPUT TYPE = "Checkbox" NAME = "SaveLogin"> Save Login as a Cookie?<P>
<INPUT TYPE = "Submit" VALUE = "Login">
<INPUT TYPE = "RESET">
</FORM>
</BODY>
</HTML>
2. Close and save the file.
3. Open the checkLogin.asp file and make the following changes.
<%
Dim strEmail
If Request.QueryString("cookie") = 1 Then
strEMail = Request.Cookies("SavedLogin")("Email")
Else
strEMail = Request.Form("email")
End If
Dim bLoginSaved
If Request.Form("SaveLogin") = "on" Then
Response.Cookies("SavedLogin")("EMail") = Request.Form("email")
Response.Cookies("SavedLogin")("pw") = Request.Form("password")
Response.Cookies("SavedLogin").Expires = Date + 30
bLoginSaved = True
Else
bLoginSaved = False
End If
%>
<HTML>
<HEAD>
<TITLE>Cookie Test - Check Login</TITLE>
</HEAD>
<BODY>
<%
If bLoginSaved Then
Response.Write "Saving Login information to a cookie<HR>"
End If
%>
Thank you for logging into the system.<P>
<%
If Request.QueryString("cookie") = 1 Then
Response.Write "Login submitted via cookie<P>"
End If
%>
E-Mail address confirmation: <%= strEMail%>
</BODY>
</HTML>
4. Now when you view the login.asp page in your browser, it automatically detects once you've logged in previously and takes you to CheckLogin.asp and displays an appropriate message:
|
|
How It Works
In this example, we have made changes to both the login.asp file and the checkLogin.asp file. The changes to login.asp will be used to detect if a cookie has been set to save the login information.
<%
If Request.Cookies("SavedLogin").HasKeys Then
Response.Redirect "CheckLogin.asp?cookie=1"
End If
%>
This section of ASP code that has been added to the top of the login.asp page will check to see if a cookie has been set. If you recall from the previous example, the cookie that is set actually contains two keys: one for the e-mail and one for the password. We can determine if the correct cookie has been set by checking to see if the cookie named SavedLogin has keys. This is why we named the file login.asp earlier.
If the correct cookie has been set, then we will use the Redirect method of the Response object to send the browser to the CheckLogin.asp page. We use the Redirect method rather than the Server.Transfer method, as we want to transmit a query string as well, and as we mentioned in the previous chapter , Server.Transfer is unable to do this. To notify this page that the request is due to the result of a cookie being read, we will set a query string parameter. We will then be able to check for this value when we are processing the checkLogin.asp page.
<%
Dim strEmail
If Request.QueryString("cookie") = 1 Then
strEMail = Request.Cookies("SavedLogin")("Email")
Else
strEMail = Request.Form("email")
End If
In the CheckLogin.asp page, we will first add some code that will determine if the page was requested by the redirection from the login.asp page. We set a query string parameter called cookie when we redirected the browser to this page. By checking to see if its value is set to 1, we will know if this page was called due to a cookie login.
There are two possible places that the user's email address can come from. If they have selected to save their logon information in a cookie, then their email address can be retrieved from that cookie. If they have entered their email address directly, then we can recover it from the Form collection of the Request object. In either case, we want to save its value into a local variable. This will allow us to use it later in the page, without having to check which method it was supplied by again.
<%
If Request.QueryString("cookie") = 1 Then
Response.Write "Login submitted via cookie<P>"
End If
%>
E-Mail address confirmation: <%= strEMail%>
We want to display an indication to the user that their login information was supplied via a cookie. The query string parameter cookie being set to 1 indicates this. If this is the case, then we will display a message. We also need to change the Response.Write shortcut that displays the email address that the user logged on with. Earlier in the page, we stored the value in the strEmail local variable. We will now display the contents of that variable here.
All that would be left to do is add the proper user authentication code, and you can have a workable user login system for your web site. Later in the book, we will take a look at how to insert and retrieve information from databases. You can then tie this method of user login with the databases and have yourself a very robust authentication system.
However, tracking users with ASP doesn't just end with cookies, it also incorporates two objects that provide a more advanced method of dealing with the tracking of a visitor through the site, the Application and Session objects.
| << 8.1.1- Tracking Users | Chapter8 | 8.2.0- The Application Object >> |

RSS




