Cookies and Sessions
Cookies and Sessions
Cookies and Sessions
http://www.flickr.com/photos/torkildr/3462607995/
HTTP is “stateless”
• Reminder:
– Cookie = a piece of data that is automatically
copied between the client and server
Browser Server
Type username
& password Send username
& password
Authenticate
Cookie =
usernm&pwd
Click a link
or whatever Request page Warning
(send cookie) This design contains a
serious security hole.
Send back
page
A more secure way of cookies+login
Filesystem
Browser Server
or Database
Type username
& password Send username
& password
Authenticate
Store a random number
Cookie = the valid only for next 10 minutes
random #
Click a link
or whatever Request page
(send cookie) Check if the number is right;
if so, give another 10 minutes
Send back
page
Session = state stored across requests
<?php
session_start(); // MUST BE the 1st line of your php
if (isset($_SESSION['numhits']))
$_SESSION['numhits'] = $_SESSION['numhits']+ 1;
else
$_SESSION['numhits'] = 1;
<?php
$nhits = isset($_COOKIE['numhits']) ?
$_COOKIE['numhits'] : 0;
$nhits = $nhits + 1;
setcookie('numhits', $nhits, time()+86400*365);
/* expires in 365 days */
• Cookies
– Little bits of data that are stored on client but also
copied automatically to the server
– Useful for storing little bits of data on the client, but
they are visible to everybody
• So don't store sensitive data in cookies
• Sessions
– Data is stored on the server (e.g., filesystem), keyed by
a random number
– The random number is sent as a cookie to the browser
– And the random number expires after a little while
When to use cookies vs sessions
• Passwords
• Credit card numbers
• Social security numbers
• Student ID numbers
• Birthdates
• List of diseases the user has contracted
• Anything that must be kept secret
Yet another caveat