Web Programming Step by Step, 2nd Edition

Lecture 12: Cookies

Reading: 14.1 - 14.2

Except where otherwise noted, the contents of this document are Copyright 2012 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

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

Setting a cookie in PHP

setcookie("name", "value");
setcookie("username", "martay");
setcookie("age", 19);
  • 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

What cookies have been set?

Cookies in Chrome Cookies in Firefox

Expiration / persistent cookies

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

Deleting a cookie

setcookie("name", FALSE);
setcookie("CouponNumber", FALSE);

Clearing cookies in your browser

remove cookies in Chrome remove cookies in Firefox

Cookie scope and attributes

setcookie("name", "value", expire, "path", "domain", secure, httponly);

Common cookie bugs