Cookies and Sessions

CSE 190 M (Web Programming) Spring 2007

University of Washington

Reading: Sebesta 12.12 - 12.13, 10.6
References: sessions, cookies; Codewalkers

Except where otherwise noted, the contents of this presentation are © Copyright 2007 Marty Stepp and are licensed under the Creative Commons Attribution 2.5 License.

Valid XHTML 1.0 Strict Valid CSS!

Stateful client/server interaction

amazon cookie

Sites like 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?


How cookies are sent

cookie exchange

Myths about cookies

How long does a cookie exist?

Where are the cookies on my computer?

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");

  • 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);

What is a session?

How sessions are established


Sessions in PHP: 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

Browsers that don't support cookies


# Generate a URL to link to one of our site's pages
$orderUrl = "/order.php?PHPSESSID=" . session_id();

Session timeout

Practice problem: remembering query