Chapter 12
Chapter 12
Chapter 12
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 1
Objectives
Applied
1. Use any of the functions and techniques presented in this chapter
as you use cookies and session tracking in your applications.
Knowledge
1. Describe the use of cookies, and distinguish between per-session
and persistent cookies.
2. Describe the use of session tracking.
3. Describe the use of the $_COOKIE and $_SESSION variables.
4. Describe the use of the functions for working with cookies and
sessions.
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 2
Examples of cookies
PHPSESSID=D1F15245171203E8670487F020544490
user_id=87
[email protected]
userName=jsmith
passwordCookie=opensesame
Terms
cookie
per-session cookie
persistent cookie
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 3
How cookies work
A cookie is a name/value pair that is stored in a browser.
On the server, a web application creates a cookie and sends it to the
browser.
On the client, the browser saves the cookie and sends it back to the
server every time it accesses a page from that server.
By default, cookies only last until the user closes his or her web
browser. However, cookies can be set to persist in the user’s
browser for up to three years.
Some users disable cookies in their browsers.
Browsers generally accept only 20 cookies from each site and 300
cookies total.
Browsers can also limit each cookie to 4 kilobytes.
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 4
The syntax of the setcookie function
setcookie($name, $value, $expire, $path,
[$domain, $secure, $httponly])
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 5
Getting the value of a cookie from the browser
$userid = $_COOKIE['userid']; // $userid is 'rharris'
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 6
How to enable or disable cookies in Firefox 3.6
1. Open the Tools menu and select the Options command.
2. Click on the Privacy tab.
3. Use the “Accept cookies from sites” check box to enable or
disable cookies.
Server
Web server Web server Web server
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 8
How PHP keeps track of sessions
Client
Browser Browser Browser
PHPSESSID=a6oqkb57f2... PHPSESSID=a6oqkb57f2...
Server
PHP PHP PHP
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 9
Start a new session or resume a previous session with the
default cookie parameters:
session_start();
session_set_cookie_params($lifetime, '/');
session_start();
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 11
The global $_SESSION variable: an associative array
that stores the data for the session.
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 12
How to set and get arrays
Set an array in a session
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 13
How to remove variables from a session
• Remove a session variable
unset($_SESSION['cart']);
• Remove all session variables
$_SESSION = array();
• Note: don’t use unset on the entire $_SESSION array, as it causes
unpredictable results
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 14
How to end a session
However: this doesn’t delete the session cookie from the user’s
browser.
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 15
How to completely remove the session data from
both the client and the server:
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 16
Functions to manage sessions
session_name()
session_id([$id])
session_write_close()
session_regenerate_id()
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 17
A Simple Shopping Cart Application
The Add Item page
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 19
The Cart page
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 20
The index.php file
<?php
// Start session management with a persistent cookie
$lifetime = 60 * 60 * 24 * 14; // 2 weeks in seconds
session_set_cookie_params($lifetime, '/');
session_start();
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 21
The index.php file (continued)
// Include cart functions
require_once('cart.php');
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 22
The index.php file (continued)
case 'update':
$new_qty_list = $_POST['newqty'];
foreach($new_qty_list as $key => $qty) {
if ($_SESSION['cart12'][$key]['qty'] != $qty) {
update_item($key, $qty);
}
}
include('cart_view.php');
break;
case 'show_cart':
include('cart_view.php');
break;
case 'show_add_item':
include('add_item_view.php');
break;
case 'empty_cart':
unset($_SE[‘cart12’]);
include('cart_view.php');
break;
}
?>
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 23
The cart.php file
<?php
// Add an item to the cart
function add_item($key, $quantity) {
global $products;
if ($quantity < 1) return;
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 24
The cart.php file (continued)
// Add item
$cost = $products[$key]['cost'];
$total = $cost * $quantity;
$item = array(
'name' => $products[$key]['name'],
'cost' => $cost,
'qty' => $quantity,
'total' => $total
);
$_SESSION['cart12'][$key] = $item;
}
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 25
The cart.php file (continued)
// Update an item in the cart
function update_item($key, $quantity) {
global $products;
$quantity = (int) $quantity;
if (isset($_SESSION['cart12'][$key])) {
if ($quantity <= 0) {
unset($_SESSION['cart12'][$key]);
} else {
$_SESSION['cart12'][$key]['qty'] = $quantity;
$total = $_SESSION['cart12'][$key]['cost'] *
$_SESSION['cart12'][$key]['qty'];
$_SESSION['cart12'][$key]['total'] = $total;
}
}
}
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 26
The cart.php file (continued)
// Get cart subtotal
function get_subtotal () {
$subtotal = 0;
foreach ($_SESSION['cart12'] as $item) {
$subtotal += $item['total'];
}
$subtotal = number_format($subtotal, 2);
return $subtotal;
}
?>
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 27
The add_item_view.php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css"
href="main.css"/>
</head>
<body>
<div id="page">
<div id="header">
<h1>My Guitar Shop</h1>
</div>
<div id="main">
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 28
The add_item_view.php file (continued)
<h1>Add Item</h1>
<form action="." method="post">
<input type="hidden" name="action"
value="add"/>
<label>Name:</label>
<select name="productkey">
<?php foreach($products as $key => $product) :
$cost = number_format($product['cost'], 2);
$name = $product['name'];
$item = $name . ' ($' . $cost . ')';
?>
<option value="<?php echo $key; ?>">
<?php echo $item; ?>
</option>
<?php endforeach; ?>
</select><br />
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 29
The add_item_view.php file (continued)
<label>Quantity:</label>
<select name="itemqty">
<?php for($i = 1; $i <= 10; $i++) : ?>
<option value="<?php echo $i; ?>">
<?php echo $i; ?>
</option>
<?php endfor; ?>
</select><br />
<label> </label>
<input type="submit" value="Add Item"/>
</form>
<p><a href=".?action=show_cart">
View Cart</a></p>
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 30
The cart_view.php file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css"
href="main.css"/>
</head>
<body>
<div id="page">
<div id="header">
<h1>My Guitar Shop</h1>
</div>
<div id="main">
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 31
The cart_view.php file (continued)
<h1>Your Cart</h1>
<?php if (count($_SESSION['cart12']) == 0) : ?>
<p>There are no items in your cart.</p>
<?php else: ?>
<form action="." method="post">
<input type="hidden" name="action"
value="update"/>
<table>
<tr id="cart_header">
<th class="left">Item</th>
<th class="right">Item Cost</th>
<th class="right">Quantity</th>
<th class="right">Item Total</th>
</tr>
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 32
The cart_view.php file (continued)
<?php foreach( $_SESSION['cart12']
as $key => $item ) :
$cost = number_format($item['cost'], 2);
$total = number_format($item['total'], 2);
?>
<tr>
<td>
<?php echo $item['name']; ?>
</td>
<td class="right">
$<?php echo $cost; ?>
</td>
<td class="right">
<input type="text"
class="cart_qty"
name=
"newqty[<?php echo $key; ?>]"
value=
"<?php echo $item['qty']; ?>"/>
</td>
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 33
The cart_view.php file (continued)
<td class="right">
$<?php echo $total; ?>
</td>
</tr>
<?php endforeach; ?>
<tr id="cart_footer">
<td colspan="3"><b>Subtotal</b></td>
<td>$<?php echo get_subtotal(); ?></td>
</tr>
<tr>
<td colspan="4" class="right">
<input type="submit"
value="Update Cart"/>
</td>
</tr>
</table>
<p>Click "Update Cart" to update quantities.
Enter a quantity of 0 to remove an item.
</p>
</form>
<?php endif; ?>
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 34
The cart_view.php file (continued)
<p><a href=".?action=show_add_item">
Add Item</a></p>
<p><a href=".?action=empty_cart">
Empty Cart</a></p>
Murach's PHP and MySQL, C12 © 2010, Mike Murach & Associates, Inc. Slide 35