University of Washington CSE 154

Section 9: Cookies

Except where otherwise noted, the contents of this document are Copyright © Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

Recall: Setting cookies in PHP

setcookie("name", "value");
...
$variable = $_COOKIE["name"];   # retrieve value of cookie later
setcookie("username", "martay");
setcookie("age", 19);
...
if (isset($_COOKIE["username"])) {
	$username = $_COOKIE["username"];
	print("Welcome back, $username.\n");
}

Exercise : Longcat Count (by Phil Sheperd)

top
bottom

Use a cookie (slides) to count the number of times the user has viewed longcat.php. Display this count to the user on the page, e.g. "You have visited 7 time(s)." (sample solution) For added challenge:

Exercise Solution

Exercise : Prize (by Michael Beswetherick)

prize.php is a travel site. We want roughly every 10th visitor to win a "free trip". (sample solution)

Exercise Solution

Exercise : Birthdays (by Phil Sheperd)

cake What day of the month were you born on? Let's check the box for everyone's day in birthdays.php. The form submits to itself, but if you leave the page and come back, it forgets what boxes were checked.

Exercise Solution