Setting and Retrieving Cookies

Up to this point, you've seen different ways to use forms and simple links to collect user data, to make that data available to another page, and to make use of it on that page. In spite of their differences, though, form and querystring variables have something important in common: Each is good for sending data from one page to another, but after that they vaporize into the forgetfulness of the HTTP protocol.

When you build Web applications, you will often want certain pieces of data to persist beyond a single request/response transaction, and forms and querystrings won't do for that. However, other variable types do persist beyond a single transaction. How is that possible, given the limitations of the HTTP protocol? The answer is that their data is stored on a hard drivethe user's or the server'sand retrieved or set as a part of every request/response transaction that requires that data.

One such variable type is the cookie. Cookies are tiny text files that are written onto user's hard drives. You can save cookies on user's hard drives and retrieve them across multiple pages. In this manner, you can maintain state in spite of the stateless HTTP protocol.

NOTE

Many users are concerned about cookies and security. In many instances, this concern is unfounded, since cookies can't be used to infect a computer with a virus, and the only site that can read a cookie is the site that set the cookie. However, cookies persist on a computer's hard drive, regardless of which actual user is logged in. Thus, storing credit card information in a cookie becomes dangerous when the user is working from a public terminal or a workstation that is shared with other colleagues. Developers should either not store anything sensitive in a cookie, such as a credit card number or a password, or the site should at least provide users with the option of whether to save the information.


In this task, you will learn how to set and retrieve cookies. You'll use the form application again, but this time, when the form is submitted and the user is redirected to test_form_processor.asp, their first and last name will be stored in a cookie on their hard drive. Then, you'll create a third page that requests these valueswithout using form or querystring variablesto demonstrate how the firstName and lastName variables can persist beyond a single HTTP request/response transaction.

  1. Open test_form_processor.asp.

    As you'll recall, this page is expecting the firstName and lastName variables to appear as a querystring; in fact, it outputs these values in the page's lone line of text: "Thank you, {QueryString.firstName} {QueryString.lastName}, for filling out my form."

    In a moment, you'll capture those same values, not for the purpose of outputting them in body text, but rather to save them as cookies to the user's hard drive.

  2. In code view, place the insertion point at the end of the line of code that precedes the opening <html> tag (line 3 in ASP and line 2 in ColdFusion). Press Enter/Return three times to add some blank space.

    graphics/05fig18.gif

    In a moment you will manually add some code, so you need to make space for it. Notice that you're adding the code before the HTML document proper, which begins with the <html> element. Server code is often placed outside the HTML document, which makes it easier to find and edit. And don't forget: When the page is output from the server to the client, the server code is stripped out, so users will never see this code.

  3. Type the code block below, as appropriate.

    For ASP:

    <% Response.Cookies("firstName") = Request.QueryString("firstName") %>
    <% Response.Cookies("firstName").Expires = Date+30 %>
    <% Response.Cookies("lastName") = Request.QueryString("lastName") %>
    <% Response.Cookies("lastName").Expires = Date+30 %>
    

    For ColdFusion:

    <cfcookie name="firstName" expires="never" value="#url.firstName#">
    <cfcookie name="lastName" expires="never" value="#url.lastName#">
    

    graphics/05fig19.gif

    Before discussing the particulars of this code, I'd like to point out that there is no visual way to write a cookie using Dreamweaver, so you have to write the code yourself. While Dreamweaver can help you develop dynamic Web sites, you have to be willing to do some hand-coding if you really want to build dynamic sites. If you've been studying the code (as you should have been) up to this point, you can probably already understand how the code works.

    Though the syntax between ASP and ColdFusion varies markedly, both sets of code work the same way. They create two new cookie variables, one named firstName and the other named lastName. As before, we are naming two completely different variables with the same names (QueryString.firstName and Cookies.firstName, with a comparable pair for the last name), but their different scopes prevent any possible confusion. Both specify expiration dates (30 days from today in ASP and never in ColdFusion). Finally, both specify the new cookie variable's value as the current value of QueryString.firstName and QueryString.lastName.

    In other words, the values of the new cookie variables are dynamically set. Not only can you set variables to static, hard values, such as Cat or Dog, but you can also create variables to hold contents drawn from other variables. Here, the cookie variables are dynamically set with the contents of the querystring variables.

  4. Back in design view, create a new paragraph below the existing one, and type Check cookie. Link the word cookie to a page named test_form_processor_cookies.asp. Save and upload this page.

    graphics/05fig20.gif

    This new page, test_form_processor_cookies.asp, doesn't exist yet, but you'll create it in a moment.

    Before you create this new page, based on what you have learned so far in this lesson, can you guess what you'll need to do to display the two cookie variables on that page?

  5. Create a new ASP/VBScript or ColdFusion XHTML-compliant page, and save it as test_form_processor_cookies.asp.

    Creating new dynamic pages should be familiar to you now.

  6. In design view, type Hi, !

    Typing text to be used with dynamic pages often looks bizarre, because a portion of the text is hard-coded, and a portion of it is going to be loaded dynamically.

    TIP

    Because your text is coming from two different sources (static XHTML and a dynamic data source), be sure to double-check your grammar and punctuation, to ensure that the text works as a unit once it is all assembled.

  7. In the Bindings panel, click the New Binding (+) button. ASP users should choose Request Variable, and then specify Request.Cookies and firstName. ColdFusion users simply choose Cookie Variable and type firstName in the dialog.

    Adding cookie bindings is just like adding querystring and form bindings.

  8. Repeat step 7 to add the lastName cookie to the Bindings panel.

    As ever, the Bindings panel updates to show you the variables that you've added.

    One difference in the Bindings panel between ASP and ColdFusion is that ASP displays variables on a page-by-page basis, whereas the bindings ColdFusion users created on other pages are available throughout the site. The practical consequence is that while an ASP user's Bindings panel at this point shows only the two cookie variables, a ColdFusion user's Bindings panel at this point shows all of the bindings you have created for the site.

    graphics/05fig21.gif

  9. Position the insertion point before the exclamation point, select Cookies.firstName (ASP) or Cookie > firstName (ColdFusion) in the Bindings panel, and click Insert. Repeat to add the last name as well.

    At this point in the lesson, you should be familiar with this routine.

    graphics/05fig22.gif

  10. Save and upload the page. Click test_form.asp in the Site panel, and press F12 to test. Fill out the form, click Submit, then follow the Check cookie link.

    As you would expect, it works. Even though the data started on the first page, you got it to display on the third. The information was pulled not from the URL or the request body as form variables, but rather from your hard drive.

    NOTE

    As before, ASP users may need to add a non-breaking space character (&nbsp;) between the first and last names, to prevent them from running together.

    NOTE

    Because HTTP is limited to request/response transactions, the server does not have direct access to the hard drive, so the cookie variables are passed from the hard drive to the server through the request. However, the source value itself is on the hard drive.

    graphics/05fig23.gif

  11. Close your browser. Return to Dreamweaver, select test_form_processor_cookies.asp in the Site panel, and press F12.

    Earlier, when you did this experiment with test_form_processor.asp, it didn't work, because there was no data in the querystringthat data was lost as soon as you closed your browser. ASP left the text blank, while ColdFusion threw an error. But when you try the same experiment using cookies, even though you closed the browser, the data persisted, because it was saved on your hard drive as a cookie. As you can see, cookies are a powerful way to create a set of persistent data that you can access across multiple pages throughout the site.