170 likes | 281 Views
Chapter 12. Cookies and Sessions Part 1. Stateless Protocol. Hypertext Transfer Protocol (HTTP) is stateless No shopping cards No logging. Cookies & Session. Cookies Store data in the user’s browser Session Store data on the server More secure. Example. includes/ login_page.inc.php
E N D
Chapter 12 Cookies and Sessions Part 1
Stateless Protocol • Hypertext Transfer Protocol (HTTP) is stateless • No shopping cards • No logging
Cookies & Session • Cookies • Store data in the user’s browser • Session • Store data on the server • More secure
Example • includes/login_page.inc.php • Displays errors • Display form and calls login.php on submit • Script 12.1 on page 369 • Purpose: Login form
Example • includes/login_functions.inc.php • function redirect_user($page=‘index.php’) • function check_login($dbc, $email, $pass) • Script 12.2 on pages 372-3 • Purpose: Validation of login
Example • login.php • If form is submitted • require ('includes/login_functions.inc.php'); • check_login($dbc, $email, $pass) • Set cookies • Redirect to loggedin.php • include login_page.inc.php • Script 12.3 on pages 378 • Purpose: User interface – Central manager
Example • loggedin.php • If (cookies are not set) • Redirect to login.php • Welcome page • Link to logout • Script 12.4 on page 381 • Purpose: Page when logged in
Example • logout.php • If (cookies are not set) • Redirect to index.php • Delete cookies • Script 12.6 on page 385 • Purpose: Page when logged out
login.php • Script 12.3 on pages 378 • http://cscdb.nku.edu/csc301/frank/ch12/login.php • ch12\script_12_03\login.php
login.php list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']); if ($check) { // OK! // Set the cookies: setcookie ('user_id', $data['user_id']); setcookie ('first_name', $data['first_name']); // Redirect: redirect_user('loggedin.php');
function check_login • Script 12.2 on pages 372-3 • ch12\login_functions.inc.php
function check_login $q = "SELECT user_id, first_name FROM users WHERE email='$e' AND pass=SHA1('$p')"; $r = @mysqli_query ($dbc, $q); // Run the query. // Check the result: if (mysqli_num_rows($r) == 1) { // Fetch the record: $row = mysqli_fetch_array ($r, MYSQLI_ASSOC); // Return true and the record: return array(true, $row);
function check_login return array(false, $errors);
function redirect_user • Script 12.2 on pages 372-3 • ch12\login_functions.inc.php
login_page.inc.php • Script 12.1 on page 369 • ch12\login_page.inc.php
loggedin.php • Script 12.4 on page 381 • ch12\script_12_04\loggedin.inc.php echo "<h1>Logged In!</h1> <p>You are now logged in, {$_COOKIE['first_name']}!</p> <p><a href=\"logout.php\">Logout</a></p>";
logout.php • Script 12.6 on page 385 • ch12\script_12_06\logout.php // Delete the cookies: setcookie('user_id', '', time()-3600, '/', '', 0, 0); setcookie('first_name', '', time()-3600, '/', '', 0, 0);