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

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.