Sessions and Cookies,
State Management
Dr. Michele C. Weigle
CS 312 - Internet Concepts
Old Dominion University
Much of these slides are based on materials and notes from Dr. Ralph Grove
This work is licensed under a
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
What is a Session?
• HTTP is stateless
– each request-response transaction is self-contained and
independent
– no state, or memory, saved across transactions
• But, we still need some way to connect multiple
requests to the same user (e.g., online shopping)
– session - sequence of requests from each individual user
CS 312 - Internet Concepts / Weigle 2
How To Manage Sessions?
• One way is to use cookies
• Cookie is a piece of state information a server stores in a
user's browser
– Set-cookie HTTP response header
• Browser will present the cookie to the same server on each
request to that server
– Cookie HTTP request header
• Servers can delete cookies or attach expiration times
CS 312 - Internet Concepts / Weigle 3
HTTP Client-Server Interaction
• Server sends "cookie"
to browser in response
message
– Set-cookie: <value>
• Browser presents cookie in
later requests to same server
– cookie: <value>
• Server matches cookie with
server-stored information
CS 312 - Internet Concepts / Weigle 4
Cookie Lifetime/Restrictions
Set-Cookie: <cookie-name>=<cookie-value>
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date> YYYY-MM-DD HH:MM:SS
Set-Cookie: <cookie-name>=<cookie-value>; Max-Age=<non-zero-digit> seconds of lifetime
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>
Set-Cookie: <cookie-name>=<cookie-value>; Path=<path-value>
Set-Cookie: <cookie-name>=<cookie-value>; HTTPS only
Secure
Set-Cookie: <cookie-name>=<cookie-value>; hidden from JavaScript
HttpOnly
// Multiple attributes are also possible, for example:
Set-Cookie: <cookie-name>=<cookie-value>; Domain=<domain-value>; Secure;
HttpOnly
Refs: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
RFC 6265, "HTTP State Management Mechanism", https://tools.ietf.org/html/rfc6265
CS 312 - Internet Concepts / Weigle 5
Cookies and PHP
• Specified on the server with
setcookie(name, value, expiration);
– if expiration not set, cookie removed at browser
restart, called a session cookie
• $_COOKIE - associative array holding cookie data on
the server
CS 312 - Internet Concepts / Weigle 6
Simple Cookie Example
• set_cookie.php
– form that sends name/value pair to
set_cookie_action.php
– displays the last cookie set
• set_cookie_action.php
– sets the cookie (name=value) with expiration date 1 hour in
future
– redirects back to set_cookie.php
CS 312 - Internet Concepts / Weigle 7
set_cookie.php
<h2>Set a Cookie:</h2>
<form method="POST"
action="set_cookie_action.php">
<p>Name: <input type="text" name="name"/>
Value: <input type="text"
name="value"/>
<input type="submit" value="Send"/>
</p>
</form>
<hr/>
<h2>Last Cookie Added:</h2> returns the key of the last item added to the array
<?php
$last_ind = count($_COOKIE)-1; displays the key and value
$last_key = array_keys($_COOKIE)[$last_ind];
echo $last_key . " = " .
$_COOKIE[$last_key]; https://www.cs.odu.edu/~mweigle/cs312/rgrove/session/set_cookie.php.txt
?> CS 312 - Internet Concepts / Weigle 8
set_cookie_action.php
<?php
// get the cookie name and value from the form, and create a cookie
$cookie_name = $_REQUEST['name'];
$cookie_value = $_REQUEST['value'];
setcookie($cookie_name, $cookie_value, time() + 3600, "/"); // good for
1 hr
redirect the user back to set_cookie.php
header('Location: set_cookie.php');
?> https://www.cs.odu.edu/~mweigle/cs312/rgrove/session/set_cookie_action.php.txt
View with Web Developer > Network tab
https://www.cs.odu.edu/~mweigle/cs312/rgrove/session/set_cookie.php to see cookies
CS 312 - Internet Concepts / Weigle 9
Ref: http://www.qcitr.com/demos/includes/index.php
Redirect vs. Forward
header('Location: next_page.php'); require('next_page.php');
• often used to reset dialog (e.g., after checkout) • often used within dialog
• browser address bar says "next_page.php" • browser address bar doesn't
change (stays at the last request)
Client Server
Client Server
enter Submit on
pageone.php enter Submit on
pageone_action.php pageone_action.php
pageone.php
response header forwards using
request includes Location require()
next_page.php
next_page.php display next_page.php
display response
response total 2 HTTP transactions returned
returned total 1 HTTP transaction
CS 312 - Internet Concepts / Weigle 10
Cookies and Sessions
• Cookie
– stored on the user's computer
– less secure than session because user can tamper with cookie
– exists until it expires
• can be used for multiple browsing sessions
• Session
– variable that is kept alive on the server side when someone
navigates to a page
– use this info to track the user throughout the site
– only exists while user's browser is open
CS 312 - Internet Concepts / Weigle 11
Sessions
• A session can record any of a Client
user's actions ID
– e-commerce example: user id, login cookie
status, shopping cart items, last
page visited, location Server
temporary
• Session records only temporary session
web
session-related info app
• For permanent storage, use a permanent
database
database
CS 312 - Internet Concepts / Weigle 12
Advantages of Using Sessions and Cookies
• Don't have to worry about passing info about users with form
data or through query string
• All data is stored temporarily on the server
– session destroyed when browser closed
• Don't have to worry about people trying fake other users
through parameters in the address bar
– session data is unavailable to users
• Main difference between sessions and cookies:
– amount of time info is available
CS 312 - Internet Concepts / Weigle 13
Sessions in PHP
• Each session gets a unique session ID via a cookie
(PHPSESSID)
• Can store session state in the server's local file
system
• Can retrieve session state based on the session ID
• Can transport session from page to page
CS 312 - Internet Concepts / Weigle 14
How to Associate Correct Session with Client?
Session-Cookie: PHPSESSID = tq23s71unv22m5mpoqlksj3ig0 random id
ID Client Server
sessid session [ID]
cookie
• After receiving the cookie, with each subsequent request, client sends
sessid cookie
• At end of session, server deletes session and erases cookie
• Server can read/write session as needed
CS 312 - Internet Concepts / Weigle 15
Sessions in PHP
• session_start() create or attach existing session
• $_SESSION['userid'] = $userid add value to session with key
'userid'
• $_SESSION['userid'] get value from
session
• unset($_SESSION['userid']) remove value from session
• session_destroy() delete session
• session_id() get
session ID
CS 312 - Internet Concepts / Weigle 16
session_start()
• creates a new session or resumes an existing
session
• each page participating in a session should call this
at the very beginning of the page
CS 312 - Internet Concepts / Weigle 17
$_SESSION
• Global associative array that holds the session state
– $_SESSION['userid'] = $user
• stores the value of $user in the session state as
userid
• Entire $_SESSION array is saved when a page
finishes
• Entire $_SESSION array is recovered when a page
calls session_start() to resume a session
CS 312 - Internet Concepts / Weigle 18
Ending a Session
foreach ($_SESSION as $key=>$val) {
// destroy each session item
unset($_SESSION[$key]);
}
// destroy remaining session state
session_destroy();
CS 312 - Internet Concepts / Weigle 19
Full Example - Login and Purchase
https://www.cs.odu.edu/~mweigle/cs312/rgrove/session/login.php
CS 312 - Internet Concepts / Weigle 20
Full Example - Network Process
Client Server
GET login.php
user requests login.php
executes login.php
HTML form code
returns output
user clicks Submit POST login_action.php
userid
executes login_action.php
stores userid in session
forwards to product.php
executes product.php
HTML form code returns output
CS 312 - Internet Concepts / Weigle 21
Full Example - Network Process
Client Server
POST product_action.php
user enters product and Purchase, product
clicks Purchase executes product_action.php
stores product in session
forwards to product.php
executes product.php
HTML form code returns output
user clicks Checkout POST product_action.php
Checkout
executes product_action.php
forwards to checkout.php
CS 312 - Internet Concepts / Weigle 22
Full Example - Network Process
Client Server
executes checkout.php
HTML form code
returns output
user clicks Complete
Purchase POST checkout_action.php
executes checkout_action.php
deletes session
creates new session
Location: login.php redirects to login.php
browser processes
GET login.php
redirect
executes login.php
HTML form code
returns output
CS 312 - Internet Concepts / Weigle 23
login.php
<?php
// start a new session
session_start();
?>
<!DOCTYPE html>
...
<form method="POST"
action="login_action.php">
Userid: <input type="text" name="userid" />
...
<p><input type="submit" value="Login"/></p>
...
CS 312 - Internet Concepts / Weigle 24
login_action.php
<?php
session_start(); // start or join session
$userid = $_REQUEST['userid'];
if($userid == null) {
require('login.php'); // return to login
screen
}
else {
$_SESSION['userid'] = $userid; // add to
session
$_SESSION['message'] = "Login Successful";
require('product.php'); // forward to
product page
} CS 312 - Internet Concepts / Weigle 25
product.php
<?php
if (session_id() == "" || !isset($_SESSION)) {
// redirect to login page if no session exists
header("Location: login.php");
} else {
session_start();
}
?>
<!DOCTYPE html>
...
<p>Userid: <?php echo $_SESSION['userid']; ?></p>
<form method="POST" action="product_action.php">
...
<input type="text" name="product">
<input type="submit" name="action"
value="Purchase">
<br/><input type="submit" name="action"
value="Checkout">
</form> CS 312 - Internet Concepts / Weigle 26
product_action.php
<?php
session_start(); // join or start a session
if ($_REQUEST['action'] == 'Purchase') {
$_SESSION['*p'.(count($_SESSION)-1)] =
$_REQUEST['product'];
$_SESSION['message'] = "Purchase successful";
require('product.php');
}
else if ($_REQUEST['action'] == "Checkout"){
require("checkout.php");
}
else {
header('Location: login.php'); // bad
request
}
?> CS 312 - Internet Concepts / Weigle 27
checkout.php
<?php
if (session_id() = "" || ...
?>
<!DOCTYPE html>
...
<p> User: <?php echo $_SESSION['userid']; ?>
</p>
<p> Cart: </p>
<ul>
<?php
foreach($_SESSION as
$key=>$value) {
if
(substr($key,0,1) == '*') {
echo
"<li>" . $value . "</li>";
}
}
?>
</ul>
... CS 312 - Internet Concepts / Weigle 28
checkout_action.php
<?php
session_start();
// destroy existing session
foreach ($_SESSION as $key=>$value) {
unset ($_SESSION[$key]);
}
session_destroy();
// start new session
session_start();
session_regenerate_id();
$_SESSION['message'] = "session
ended";
header("Location: login.php"); See examples page for links to source of PHP files
?> https://www.cs.odu.edu/~mweigle/cs312/examples/index.html#sessions
CS 312 - Internet Concepts / Weigle 29
European Union (EU) and Cookies
● If your website is used by EU clients, these
cookies do not require consent:
○ Cookies used solely for communication (eg.
session cookie)
○ Cookies strictly necessary to provide
requested service
○ Generally, technical cookies, non-personal
● Other cookies, especially tracking cookies
require user consent
○ Website must post a privacy proxy
○ User must consent
Pop-up on https://www.thetimes.co.uk/
CS 312 - Internet Concepts / Weigle 30
What if the User Refuses Cookies?
• Don't allow the user to access the webpage
OR
• Encode the $PHPSESSID value as an attribute in a GET or POST
method request
– can be done via the form action
OR
action="checkout_action.php?
PHPSESSID=tq23s71unv22m"
– as a hidden form input element
For more information, see
https://www.brainbell.com/tutors/php/php_mysql/Session_Management_Without_Cookies.html
<input type = "hidden" name = "PHPSESSID"
CS 312 - Internet Concepts / Weigle 31