O'Reilly logo

Web Site Cookbook by Doug Addison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.10. Using Cookies to Remember Visitor Choices

Problem

You need to store small bits of information about your web site visitors' preferences and retrieve them on their subsequent visits to your site.

Solution

Record the settings as a cookie on a visitor's hard drive using the built-in PHP function setcookie( ), and then access it with PHP's built-in array of cookie variables associated with the current browser session, $_COOKIE.

Discussion

Browser cookies are an oft-debated and indispensable part of the Web. Privacy advocates rightfully point out that abuse can allow unscrupulous web sites to know much of the personal information and browsing habits of their visitors without their permission. But most of the world's most popular web sites—from Amazon.com to Yahoo!—would operate much differently without cookies. Whenever a site remembers your login information, or your name and address, it's using cookies to do so.

Cookies are small individual files, or indexed entries in one larger file, that store—on the visitor's own hard drive—a bit of information about a particular user for a particular web site. They typically have a name, the data to be stored, the host name of the site that controls the cookie, the file path on the host where the cookie is valid, and an expiration date. Cookies are exclusive to a specific browser on a specific computer. For example, if you have an account with the New York Times web site, you'll need a cookie on both your home and work computer to bypass the login ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required