CSE 190M Web Programming

Lecture 26: Cookies and Sessions

Reading: 14.1 - 14.4

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, Victoria Kirst and Roy McElmurry IV. 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

ASCIImation gallery

Visit your homework 6 page with the gallery query parameter in order to see everyone's custom asciimations!

			http://webster.cs.washington.edu/UW_NET_ID/hw6/ascii.html?gallery=true

14.1: Cookie Basics

Stateful client/server interaction

amazon cookie

Sites like amazon.com seem to "know who I am." How do they do this? How does a client uniquely identify itself to a server, and how does the server provide specific content to each client?

What is a cookie?

om nom nom

How cookies are sent

cookie exchange

Myths about cookies

A "tracking cookie"

tracking cookie figure

Where are the cookies on my computer?

good enough for me

How long does a cookie exist?

14.2: Programming with Cookies

Cookies in JavaScript

document.cookie = "username=smith";   // setting two cookies
document.cookie = "password=12345";
document.cookie = "age=29; expires=Thu, 01-Jan-1970 00:00:01 GMT";  // deleting a cookie
...
// (later)
var allCookies = document.cookie.split(";");    // ["username=smith", "password=12345"]
for (var i = 0; i < allCookies.length; i++) {
	var eachCookie = allCookies[i].split("=");    // ["username", "smith"]
	var cookieName = eachCookie[0];               // "username"
	var cookieValue = eachCookie[1];              // "smith"
	...
}

Cookies jQuery Plugin

<!-- using jquery.cookies.js -->
<script src="jquery.js" type="text/javascript"></script>
<script src="http://webster.cs.washington.edu/cse190m/jquery.cookies.js" type="text/javascript"></script>
$.cookies.set("username", "smith");
// (later)
alert($.cookies.get("username"));   // smith
// (much later)
$.cookies.del("username");

Setting a cookie in PHP

setcookie("name", "value");
setcookie("username", "martay");
setcookie("favoritecolor", "blue");
  • technically, a cookie is just part of an HTTP header, and it could be set using PHP's header function (but this is less convenient, so you would not want to do this):
  • header("Set-Cookie: username=martay; path=/; secure");
    

Retrieving information from a cookie

$variable = $_COOKIE["name"];   # retrieve value of the cookie
if (isset($_COOKIE["username"])) {
	$username = $_COOKIE["username"];
	print("Welcome back, $username.\n");
} else {
	print("Never heard of you.\n");
}
print("All cookies received:\n");
print_r($_COOKIE);
  • unset function deletes a cookie

Setting a persistent cookie in PHP

setcookie("name", "value", timeout);
$expireTime = time() + 60*60*24*7;   # 1 week from now
setcookie("CouponNumber", "389752", $expireTime);
setcookie("CouponValue", "100.00", $expireTime);

Removing a persistent cookie

setcookie("name", "", time() - 1);
setcookie("CouponNumber", "", time() - 1);

14.3: Sessions

What is a session?

How sessions are established

session

Sessions in PHP: session_start

session_start();

Accessing session data

$_SESSION["name"] = value;        # store session data
$variable = $_SESSION["name"];     # read session data
if (isset($_SESSION["name"])) {  # check for session data
if (isset($_SESSION["points"])) {
	$points = $_SESSION["points"];
	print("You've earned $points points.\n");
} else {
	$_SESSION["points"] = 0;  # default
}

Where is session data stored?

session cookie

Session timeout

Browsers that don't support cookies

session_start();   # same as usual

# Generate a URL to link to one of our site's pages
# (you probably won't ever need to do this)
$orderUrl = "/order.php?PHPSESSID=" . session_id();

Ending a session

session_destroy();

Exercise: Power Animal

power animal
power animal
  • Write a page poweranimal.php that chooses a random "power animal" for the user.
    • The page should remember what animal was chosen for the user and show it again each time they visit the page.
    • It should also count the number of times that user has visited the page.
    • If the user selects to "start over," the animal and number of page visits should be forgotten.

Practice problem: Power Animal

power animal
power animal

Implementing user logins

user login

Example simpsons database

students
idnameemailpassword
123Bartbart@fox.combartman
456Milhousemilhouse@fox.comfallout
888Lisalisa@fox.comvegan
404Ralphralph@fox.comcatfood
teachers
idname
1234Krabappel
5678Hoover
9012Stepp
courses
idnameteacher_id
10001Computer Science 1421234
10002Computer Science 1435678
10003Computer Science 190M9012
10004Informatics 1001234
grades
student_idcourse_idgrade
12310001B-
12310002C
45610001B+
88810002A+
88810003A+
40410004D+

Exercise: Simpsons grade display

grades
  • Write a site where Springfield Elementary students can log in to check their grades.
  • Implement a user login system that verifies proper user names and passwords.
  • A student should only be able to view his/her own grades.

"Remember Me" feature

user login

Web Storage

localStorage

// localStorage is a global javascript object
localStorage.setItem("foo", "bar");
localStorage.getItem("foo");			// bar
localStorage.foo;								 // bar

localStorage.removeItem("foo");
localStorage.getItem("foo");			// null

// delete all local storage
localStorage.clear();
	

sessionStorage

// sessionStorage is a global javascript object
sessionStorage.setItem("foo", "bar");
sessionStorage.getItem("foo");			// bar
sessionStorage.foo;								 // bar

sessionStorage.removeItem("foo");
sessionStorage.getItem("foo");			// null

// delete all session storage
sessionStorage.clear();
	

Exercise: Image Library

Check out this working example

  • Write a web page that remembers and displays a list of images.
    • Use localStorage to remember the image links
    • The delete all button should forget the whole list