0% found this document useful (0 votes)
5 views

Chapter 2 Part6+7

Uploaded by

dangcongbang978
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 2 Part6+7

Uploaded by

dangcongbang978
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

ADVANCED WEB TECHNOLOGY

Chapter 2. Master PHP Programming


Chapter 2. Master PHP Programming

Content
2.1. How to work with form data
2.2. How to code control statements
2.3. How to work with string and numbers
2.4. How to work with dates
2.5. How to work with arrays
2.6. How to work with cookie
2.7. How to work with session
2.8. How to work with functions
2.9. How to work with objects
2.10. How to work with regular expression, handle exception

C1, Slide 2
2.6. How to work with cookie
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 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.

C12, Slide 3
Examples of cookies
PHPSESSID=D1F15245171203E8670487F020544490
user_id=87
[email protected]

C12, Slide 4
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 until a specified expiration date.
 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.
 A cookie can be associated with one or more subdomain names.

C12, Slide 5
The syntax of the setcookie() function
setcookie($name, $value, $expire, $path,
$domain, $secure, $httponly)

Setting a cookie in the browser


$name = 'userid';
$value = '87';
$expire = strtotime('+1 year');
$path = '/';
setcookie($name, $value, $expire, $path);

Getting the value of a cookie from the browser


$userid = filter_input(INPUT_COOKIE, 'userid',
FILTER_VALIDATE_INT);

Deleting a cookie from the browser


$expire = strtotime('-1 year');
setcookie('userid', '', $expire, '/');

C12, Slide 6
Key terms
 cookie
 session cookie
 persistent cookie

C12, Slide 7
How to enable or disable cookies in Chrome
59
1. Open the Customize and control Google Chrome menu and
select the Settings command.
2. Scroll down and click on the “Advanced.” link.
3. In the Privacy and security section, click on the “Content
settings” link.
4. Click on the Cookies link.
5. Turn the “Allow sites to save and read cookie data” option on to
enable cookies or off to disable cookies.

C12, Slide 8
How to enable or disable cookies in IE 11
1. Open the Tools menu and select the Internet Options command.
2. Click the Privacy tab.
3. Use the slider control to enable or disable cookies, or click on the
Advanced button, check the “Override automatic cookie
handling” checkbox, configure cookies, and click the OK button.
4. To undo changes made with the slider control or in the Advanced
section, click the Default button to return to default privacy
settings.

C12, Slide 9
How to reset default security settings in IE 11
1. Open the Tools menu and select the Internet Options command.
2. Click the Security tab.
3. If not disabled, click the “Reset all zones to default level” button.

C12, Slide 10
Chapter 2. Master PHP Programming

Content
2.1. How to work with form data
2.2. How to code control statements
2.3. How to work with string and numbers
2.4. How to work with dates
2.5. How to work with arrays
2.6. How to work with cookie
2.7. How to work with session
2.8. How to work with functions
2.9. How to work with objects
2.10. How to work with regular expression, handle
exception

C1, Slide 11
2.7. How to work with session

Why session tracking is difficult with HTTP

C12, Slide 12
How PHP keeps track of sessions

C12, Slide 13
Key terms
 State
 Stateless protocol
 Session tracking
 URL encoding

C12, Slide 14
A function to start a session
session_start()

Start a session with the default cookie parameters


session_start();

C12, Slide 15
The session_set_cookie_params() function
session_set_cookie_params($lifetime, $path, $domain,
$secure, $httponly)

Start a session with custom cookie parameters


$lifetime = 60 * 60 * 24 * 365; // 1 year in seconds
session_set_cookie_params($lifetime, '/');
session_start();

C12, Slide 16
How to set and get scalar variables
Set a variable in a session
$_SESSION['product_code'] = 'MBT-1753';

Get a variable from a session


$product_code = $_SESSION['product_code'];

C12, Slide 17
How to set and get arrays
Set an array in a session
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}

Add an element to an array that’s stored in a session


$_SESSION['cart']['key1'] = 'value1';
$_SESSION['cart']['key2'] = 'value2';

Get and use an array that’s stored in a session


$cart = $_SESSION['cart'];
foreach ($cart as $item) {
echo '<li>' . $item . '</li>';
}

C12, Slide 18
How to remove variables from a session
Remove a session variable
unset($_SESSION['cart']);

Remove all session variables


$_SESSION = array();

C12, Slide 19
Functions to manage sessions
session_name()
session_id([$id])
session_write_close()
session_regenerate_id()

Get the name of the session cookie


$name = session_name(); // By default, PHPSESSID

Get the value of the session ID


$id = session_id();

Set the session ID


session_id('abc123');

C12, Slide 20
A function to end a session
session_destroy()

End a session
$_SESSION = array(); // Clear session data from memory
session_destroy(); // Clean up the session ID

C12, Slide 21
Delete the session cookie from the browser
// Get name of session cookie
$name = session_name();

// Create expire date in past


$expire = strtotime('-1 year');

// Get session params


$params = session_get_cookie_params();
$path = $params['path'];
$domain = $params['domain'];
$secure = $params['secure'];
$httponly = $params['httponly'];

setcookie($name, '', $expire, $path, $domain,


$secure, $httponly);

C12, Slide 22
The Add Item page

C12, Slide 23
The Cart page

C12, Slide 24
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();

// Create a cart array if needed


if (empty($_SESSION['cart12'])) { $_SESSION['cart12'] =
array(); }

// Create a table of products


$products = array();
$products['MMS-1754'] =
array('name' => 'Flute', 'cost' => '149.50');
$products['MMS-6289'] =
array('name' => 'Trumpet', 'cost' => '199.50');
$products['MMS-3408'] =
array('name' => 'Clarinet', 'cost' => '299.50');

C12, Slide 25
The index.php file (continued)
// Include cart functions
require_once('cart.php');

// Get the action to perform


$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'show_add_item';
}
}

// Add or update cart as needed


switch($action) {
case 'add':
$product_key = filter_input(INPUT_POST,
'productkey');
$item_qty = filter_input(INPUT_POST, 'itemqty');
add_item($product_key, $item_qty);
include('cart_view.php');
break;

C12, Slide 26
The index.php file (continued)
case 'update':
$new_qty_list = filter_input(INPUT_POST, 'newqty',
FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
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($_SESSION['cart12']);
include('cart_view.php');
break;
}

C12, Slide 27
The cart.php file
<?php
// Add an item to the cart
function add_item($key, $quantity) {
global $products;
if ($quantity < 1) return;

// If item already exists in cart, update quantity


if (isset($_SESSION['cart12'][$key])) {
$quantity += $_SESSION['cart12'][$key]['qty'];
update_item($key, $quantity);
return;
}

C12, Slide 28
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;
}

C12, Slide 29
The cart.php file (continued)
// Update an item in the cart
function update_item($key, $quantity) {
$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;
}
}
}

C12, Slide 30
The cart.php file (continued)
// Get cart subtotal
function get_subtotal() {
$subtotal = 0;
foreach ($_SESSION['cart12'] as $item) {
$subtotal += $item['total'];
}
$subtotal_f = number_format($subtotal, 2);
return $subtotal_f;
}
?>

C12, Slide 31
The add_item_view.php file
<!DOCTYPE html>
<html>
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<header>
<h1>My Guitar Shop</h1>
</header>
<main>

C12, Slide 32
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>

C12, Slide 33
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>&nbsp;</label>
<input type="submit" value="Add Item">
</form>
<p><a href=".?action=show_cart">View Cart</a></p>
</main>
</body>
</html>

C12, Slide 34
The cart_view.php file
<!DOCTYPE html>
<html>
<head>
<title>My Guitar Shop</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<header>
<h1>My Guitar Shop</h1>
</header>
<main>

C12, Slide 35
The cart_view.php file (continued)
<h1>Your Cart</h1>
<?php if (empty($_SESSION['cart12']) ||
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>

C12, Slide 36
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>
<td class="right">
$<?php echo $total; ?></td>
</tr>
<?php endforeach; ?>

C12, Slide 37
The cart_view.php file (continued)
<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 in
your cart. Enter a quantity of 0 to remove
an item.</p>
</form>
<?php endif; ?>
<p><a href=".?action=show_add_item">Add Item</a></p>
<p><a href=".?action=empty_cart">Empty Cart</a></p>
</main>
</body>
</html>

C12, Slide 38

You might also like