Publishers of technology books, eBooks, and videos for creative people

Home > Articles

This chapter is from the book

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 HTTP.

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 HTTP? The answer is that their data is stored in memory or on a hard drive—the user’s or the server’s—and 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.

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 users are redirected to test_form_processor.asp, their first and last names will be stored in cookies on their hard drives. Then, you’ll create a third page that requests these values—without using form or querystring variables—to 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 just before the <!DOCTYPE> tag (line 2 in ASP and line 1 in ColdFusion and PHP). Press Enter/Return a few times to add some blank space.

    The blank lines should precede the <DOCTYPE> tag.

    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 <DOCTYPE> 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.

    In 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
    %>
    

    In ColdFusion:

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

    In PHP:

    <?php
    setcookie('firstName', $_GET['firstName'], time() + (60*60*24));
    setcookie('lastName', $_GET['lastName'], time() + (60*60*24));
    ?>
    

    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, you probably already understand how the code works.

    Though the syntax varies markedly when you compare ASP, ColdFusion, and PHP, all three 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, never in ColdFusion, and one day for PHP). Finally, all three 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/URL 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.

    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 dynamic, 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.

  7. In the Bindings panel, click the New Binding (+) button. ASP users should choose Request Variable, and then specify Request.Cookies and firstName. ColdFusion and PHP 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/PHP is that ASP displays variables on a page-by-page basis, whereas the bindings that 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 or PHP user’s Bindings panel at this point shows all of the bindings you have created for the site.

  9. Position the insertion point before the exclamation point, select Cookies.firstName (ASP) or Cookie > firstName (ColdFusion/PHP) 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.

  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.

  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 querystring—that data was lost as soon as you closed your browser. ASP and PHP 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.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.