CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.

Slides:



Advertisements
Similar presentations
CookiesPHPMay-2007 : [‹#›] Maintaining State in PHP Part I - Cookies.
Advertisements

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
Chapter 10 Managing State Information Using Sessions.
©2009 Justin C. Klein Keane PHP Code Auditing Session 7 Sessions and Cookies Justin C. Klein Keane
Managing State Information. PHP State Information 2 Objectives Learn about state information Use hidden form fields to save state information Use query.
Chapter 10 Managing State Information PHP Programming with MySQL.
Using Session Control in PHP tMyn1 Using Session Control in PHP HTTP is a stateless protocol, which means that the protocol has no built-in way of maintaining.
CSE 154 LECTURE 13: SESSIONS. Expiration / persistent cookies setcookie("name", "value", expiration); PHP $expireTime = time() + 60*60*24*7; # 1 week.
Chapter 10 Maintaining State Information Using Cookies.
Objectives Learn about state information
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
Cookies Set a cookie – setcookie() Extract data from a cookie - $_COOKIE Augment user authentication script with a cookie.
Chapter 12 Cookies and Sessions Part 2. Setting Cookie Parameters setcookie(name, value, expiration, path, host, secure, httponly) epoch – midnight on.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
PHP Hypertext PreProcessor. Documentation Available SAMS books O’Reilly Books.
JavaScript, Fourth Edition
Working with Cookies Managing Data in a Web Site Using JavaScript Cookies* *Check and comply with the current legislation regarding handling cookies.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
Web Programming Language Week 7 Dr. Ken Cosh Security, Sessions & Cookies.
Chapter 8 Cookies And Security JavaScript, Third Edition.
12/3/2012ISC329 Isabelle Bichindaritz1 PHP and MySQL Advanced Features.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
Cookies & Session Web Technology
PHP Workshop ‹#› Maintaining State in PHP Part II - Sessions.
STATE MANAGEMENT.  Web Applications are based on stateless HTTP protocol which does not retain any information about user requests  The concept of state.
SessionsPHPApril 2010 : [‹#›] Maintaining State in PHP Part II - Sessions.
PHP Programming with MySQL Slide 10-1 CHAPTER 10 Managing State Information.
Chapter 12 Cookies and Sessions Part 1. Stateless Protocol Hypertext Transfer Protocol (HTTP) is stateless No shopping cards No logging.
Advance web Programming Managing State Information (Cookies-Session) Date: 22 April 2014 Advance web Programming Managing State Information (Cookies-Session)
COOKIES and SESSIONS. COOKIES A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each.
Web Database Programming Week 7 Session Management & Authentication.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
 A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
Cookies and Sessions in PHP. Arguments for the setcookie() Function There are several arguments you can use i.e. setcookie(‘name’, ‘value’, expiration,
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
Sessions and cookies (part 2) MIS 3501, Fall 2015 Brad N Greenwood, PhD Department of MIS Fox School of Business Temple University 11/19/2015.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
COOKIES AND SESSIONS.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
Programming for the Web Cookies & Sessions Dónal Mulligan BSc MA
Sessions and cookies MIS 3501, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 4/12/2016.
© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
The need for persistence Consider these examples  Counting the number of “hits” on a website  i.e. how many times does a client load your web page source.
CSE 154 Lecture 20: Cookies.
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
ITM 352 Cookies.
Maintaining State in PHP Part II - Sessions
Web Programming Language
Cookies and Sessions in PHP
Implementing Cookies in PHP
Cookies BIS1523 – Lecture 23.
Cookies Cookie :- A cookie is often used to identify a user. A cookie is often used to identify a user. A cookie is a small file that the server embeds.
Cookies and Sessions Part 2
Maintaining State in PHP Part II - Sessions
Web Programming Language
Web Programming Language
PHP-II.
Presentation transcript:

CHAPTER 12 COOKIES AND SESSIONS

INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from the same website. There is no way with just HTTP to track users, create shopping carts, or personalize web pages.

MAINTAINING STATE Tools: Hidden form fields Query strings Cookies Sessions

THE OPTIONS HIDDEN FORM FIELDS Example: Use $_GET or $_POST State data is temporarily stored. QUERY STRINGS Example: Creates $_GET variables that the next page can use. Storage is also temporary

THE OPTIONS COOKIES Store data in the user's Web browser May be disabled or deleted by the user Can be made to last longer SESSIONS Store data on the server itself More secure More robust (can store more data)

A LOGIN PAGE 1.A form submits the login data 2.A script validates and confirms that the necessary information was submitted 3.A database query compares the submitted information against the stored information 4.Cookies or sessions store data that reflect a successful login 5.The cookie or session will check the login status so the user won't have to login on each new page

USING COOKIES Cookies are files sent by a server to store information on the user's machine. Examples of cookies PHPSESSID=D1F E F user_id=87 userName=jsmith passwordCookie=opensesame To use cookies, they must be sent from the server to the client before any other HTML is sent.

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.

THE SETCOOKIE FUNCTION setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly]) Setting a cookie in the browser: $name = 'userid'; $value = 'rharris'; $expire = time()+60*60*24*30; $path = '/'; setcookie($name, $value, $expire, $path);

SETCOOKIE PARAMETERS setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly]) The setcookie parameter $expire : default = 0; lasts until user closes browser window; a per-session cookie. other timestamp values are persistent cookies. time in seconds since 1/1/70 or relative to the present using time() 30 minutes = 1800 seconds setcookie (name, value, time()+1800);

SETCOOKIE PARAMETERS setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly]) The setcookie parameter $path: the path on the server the cookie is available to if set to '/', the cookie is available to all directories on the current server default is the current directory (that set the cookie)

SETCOOKIE PARAMETERS setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly]) The setcookie parameter $host: the specific domain the cookie is available to '.example.com' makes the cookie visible within default is the name of the server that is setting the cookie

SETCOOKIE PARAMETERS setcookie($name, [$value, $expire, $path, $domain, $secure, $httponly]) The setcookie parameters: $secure: 1 means the cookie is available only if being sent using HTTPS default is 0 $httponly: 1 means the cookie is only available through HTTP/HTTPS and not through client-side scripts default is 0

THE LOGIN PROCESS Login Form Validate Form Input Query Database Set Cookies or Start Session OK Valid Login Incomplete Invalid login

SETTING COOKIES AFTER A SUCCESSFUL LOGIN if (….) { // Login successful // Set the cookies: setcookie ('user_id', $data['user_id']); setcookie ('first_name', $data['first_name']); // Redirect: redirect_user('logged_in.php'); }

REDIRECTING Depending on whether or not a user has successfully logged in, the code should redirect to the appropriate page. Redirection uses the header() function with the 'Location: ' string. Best practice is to use an absolute URL here: header('Location: ged_in.php');

DEFINING A URL DYNAMICALLY Better yet, instead of hard-coding it, determine it dynamically. The $_SERVER superglobal array contains several values set by the web server. The relevant ones here are: $_SERVER['HTTP_HOST'] which gives the host name $_SERVER['PHP_SELF'] which refers to the current script including its directory name

DEFINING A URL DYNAMICALLY (CONT') We also use the two functions: dirname() which returns just the directory i.e. /Ch12/ rtrim() which removes spaces or the given characters $url = ' $_SERVER['HTTP_HOST']. dirname($_SERVER['PHP_SELF']); $url = rtrim($url, '/\\'); $page='index.php'; $url.= '/'. $page;

DEFINING A URL DYNAMICALLY (CONT') The finish with: header("Location: $url"); exit(); //don't process remaining script

ACCESSING COOKIES To retrieve a value from a cookie that has been sent, use the suberglobal variable $_COOKIE[ ] setcookie ('userName', 'Smitherman'); can be referred to as: $_COOKIE['userName'] but only from another page!

TESTING THE COOKIE VALUES <?php # Script logged_in.php // The user is redirected here from login.php. // If no cookie is present, redirect the user: if (!isset($_COOKIE['user_id'])) { //redirect to index or login page } // Set the page title and include the HTML header: $page_title = 'Logged In!'; include ('../includes/header.php'); // Print a customized message: echo " Logged In! You are now logged in, ".$_COOKIE['first_name']."! Logout "; include ('includes/footer.html'); ?>

DELETING A COOKIE Cookies will automatically expire: when the user's browser closes when the expiration date/time is met Cookies can be manually deleted by: resetting the value parameter to '' setting an expiration date in the past

THINGS TO REMEMBER ABOUT COOKIES After a cookie is set, it isn't available until either the page is reloaded or another page is accessed. After a cookie is deleted, it exists until either the page is reloaded or another page has been accessed.

SESSIONS Data generated by the server and stored on the server. To start a session or resume a previous session: session_start(); This must be called before any HTML is sent back to the browser. The function will try to send a cookie called PHPSESSID and a value to the browser.

SESSIONS Once the session starts, the superglobal $_SESSION[ ] array can be used: $_SESSION['user_id'] = $data['user_id']; $_SESSION['first_name'] = $data['first_name'];

SESSIONS Any pages that attempt to use the $_SESSION[ ] superglobal, must have sessions enabled with session_start(); session_start(); will try to retrieve the PHPSESSID value from the stored cookie, or it will create a new session If a new session is started, any previous session data will no longer be available.

SESSIONS Session variables are available as soon as they are enabled (unlike cookies.) A session variable can be assigned a value and then referred to from within the same script (without reloading.)

SESSIONS Three kinds of information are stored: 1.The session identifier, PHPSESSID, is stored as a cookie by default 2.The session data which is stored as a text file on the server 3.The $_SESSION array, which is how the script accessed the data in the text file

CONTROLLING THE SESSION COOKIE To control the session cookie, use the function: session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly) $lifetime: of the cookie in seconds; required parameter $path: the sever path that the cookie is available to; default is current directory of the script setting the cookie. The other three parameters don’t usually need to be changed.

CONTROLLING THE SESSION COOKIE Start a session with custom cookie parameters: $lifetime = 60 * 60 * 24 * 365; // 1 year in seconds session_set_cookie_params($lifetime, '/'); session_start(); Note: this must occur before any HTML code is returned and session_set_cookie_params() must precede session_start();

CONTROLLING THE SESSION COOKIE The global $_SESSION variable: an associative array that stores the data for the session. 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'];

DELETING SESSION VARIABLES 1.Access the existing session using session_start(); 2.Reset the $_SESSION array 3.Use destroy_session(); to remove session data from server 4.Specify that the session cookie expires. **NOTE: There is an unset() function, but don’t use it on the entire $_SESSION array, as it causes unpredictable results.