Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.

Slides:



Advertisements
Similar presentations
LIS651 lecture 3 taming PHP Thomas Krichel
Advertisements

CookiesPHPMay-2007 : [‹#›] Maintaining State in PHP Part I - Cookies.
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.
PHP (2) – Functions, Arrays, Databases, and sessions.
Chapter 10 Managing State Information PHP Programming with MySQL.
CSE 154 LECTURE 13: SESSIONS. Expiration / persistent cookies setcookie("name", "value", expiration); PHP $expireTime = time() + 60*60*24*7; # 1 week.
Php cookies & sessions.
Chapter 10 Maintaining State Information Using Cookies.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
Lecture 7 – Form processing (Part 2) SFDV3011 – Advanced Web Development 1.
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. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures.
JavaScript, Fourth Edition
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
1 Maryland ColdFusion User Group Session Management December 2001 Michael Schuler
Slide 7-1 CHAPTER 7 Managing Multiple-Form Applications: Writing scripts with multiple screens.
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
11 1 Cookies CGI/Perl Programming By Diane Zak Objectives In this chapter, you will: Learn the difference between temporary and persistent cookies.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
PHP Workshop ‹#› Maintaining State in PHP Part II - Sessions.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
SessionsPHPApril 2010 : [‹#›] Maintaining State in PHP Part II - Sessions.
Dynamic Programming with PHP (mktime), Cookies, SQL, Authentication.
PHP Programming with MySQL Slide 10-1 CHAPTER 10 Managing State Information.
PHP. $_GET / $_POST / $_SESSION PHP uses predefined variables to provide access to important information about the server and requests from a browser.
Sessions in PHP – Page 1 of 13CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: Sessions in PHP Reading: Williams.
Web Database Programming Week 7 Session Management & Authentication.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 The Web Wizard’s Guide to PHP by David Lash.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
Database Access Control IST2101. Why Implementing User Authentication? Remove a lot of redundancies in duplicate inputs of database information – Your.
How to maintain state in a stateless web Shirley Cohen
Sessions Brendan Knight A visitor accessing your web site is assigned a unique id. This id links to specific data that remains on the server. Sessions.
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)
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.
1 CS428 Web Engineering Lecture 22 Building Dynamic Web pages (PHP - V)
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
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.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 The Web Wizard’s Guide to PHP by David Lash.
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.
Fundamentals of Web DevelopmentRandy Connolly and Ricardo HoarFundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar Fundamentals of Web DevelopmentRandy.
Programming for the Web Cookies & Sessions Dónal Mulligan BSc MA
© 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.
Managing State Chapter 13.
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.
Open Source Programming
Cookies and sessions Saturday, February 23, 2019Saturday, February 23,
Cookies and Sessions.
Presentation transcript:

Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1

2 Cookies

3 Problem…  How do you identify a particular user when they visit your site (or any page on your site) without always passing it back and forth in HTML forms?  What if they leave your site then come back later and you don't want to make them identify them again?  E.g. username

4 Use a Cookie!

5 What is a cookie?  A cookie is a particular piece of data combined with a unique id that the server sends to the browser to store  Data is stored on the browser and can be requested by the server whenever the user visits  The data is set by you. Usually a user id, but sometimes other things.  Generally one piece of info per cookie  Only the server that sent the cookie can request it from a user's browser (it's handled via the server's URL and can be specialized to particular directories or pages on that server)  The user's browser manages cookie data  What is acceptable, where stored, when to send if requested, how long to keep  The browser can set a suggested expiration time, but no guarantees!

6 Sending a Cookie  To send a cookie you MUST call the set_cookie() function before anything is output to your web browser (just like the header() function).set_cookie()  Otherwise you will get the error below:  Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3  Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3

7 Sending a Cookie Examples /* If cookie is not set, set the username as a cookie to identify the user on the next visit. Make it expire in 1 hour */ $username = 'ITM352'; /* MUST BE DONE BEFORE ANY OUTPUT! */ if (!isset($_COOKIE["userid"])) setcookie("userid", $username, time()+3600 ); /* set the expiration date to one hour ago with empty data to request the browser to delete cookie */ setcookie ("userid", "", time() ); /* see if a cookie has been set and if so print it */ if (isset($_COOKIE["userid"])) echo $_COOKIE["userid"];

8 Cookie Considerations  Limitations  Users may delete cookies  Users may disallow cookies  Some browsers don't handle them well  Only good for small bits of data (but you can use multiple cookies)  Only identifies the browser the cookie sent to, not the actual user! (someone using another person's browser will be mistaken for that user)  The only way to be sure the user is authentic is to have them log in with a username and password  Be careful!  setcookie() will always send a new cookie to the browser. If you don't want to overwrite it, just check if it exists before writing.

9 Sessions

10 Problem…  How do you keep data about a particular user around when passing from page to page without always passing it back and forth in HTML forms? What if the user goes away from the site then comes back?  E.g. You might want to keep: user authentication info, shopping cart items, user preferences. (This is not a shared data problem as we have dealt with previously. The main problem is keeping and using individual data for multiple users.)

11 Answer: Use a Session! session page1 page2 page3 identify data identify server side browser side

12 User Sessions  Start a session  session_start();  Destroy the session when you're done  session_destroy();  There are more sophisticated things you can do, e.g:  Expire sessions, unregister particular variables, custom sessions storage, cookies, etc.

13 What is a Session?  A session is a particular set of data combined with a unique user id  Data is stored on the server and connected to the user by the session id  The data is set by you  At least the user id is stored on the user's browser as a cookie or as a URL query string or browser header data  Not great, but sometimes ok is to identify user by IP-address (and this is the default for sessions)  You must manage session data  What, where, when, how-long

14 Starting Sessions  To start a session you MUST call the session_start() function before anything is output to your web browser (just like the header() function). session_start()  Otherwise you get the error below:  Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3  Warning: Cannot send session cache limiter - headers already sent (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3

15 Starting Sessions  You must use session_start() on any page that you wish to use session variables EVEN IF YOU HAVE ALREADY CALLED IT PREVIOUSLY!!!!!session_start()  You must also be sure the location where the session data will be stored is accessible (e.g. writable)  May have to specify with session_save_path();

16 Registering Session Variables  You access the session data via the $_SESSION array (which PHP manages for you)  To put a variable in the current session add it to the $_SESSION array:  $_SESSION[‘product'] = ‘gumball';  $_SESSION['size'] = 'small';  All pages that call session_start() will have access to this array—it is shared data.

17 Registering Session Variables ** Important **  Registered session variable values are static: they will only be set once when the corresponding variable is initialized.  If you want them to change dynamically along with changes to the variable, you must assign them a reference to the session variable (note the ' & ' in the code below): $aVarIdent = & $_SESSION['aVarIdent'];

18 Accessing Session Variables  Session variables are generally not automatically set in a page. You usually must access them from the $_SESSION array  $aVarIdent = $_SESSION['aVarIdent'];  $aVarIdent is local to the page only. To store it back in the session, you must use $_SESSION['aVarIdent'] = $aVarIdent;  If you want to directly affect changes, use references (create an alias)  $aVarIdent = & $_SESSION['aVarIdent'];

19 Example: User Page Hits <? session_save_path('.'); // You may need to change this session_start(); // No output before this! if (!isset($_SESSION['hitcount'])) $_SESSION['hitcount'] = 1; $hits = & $_SESSION['hitcount']; $hits++; /* Un-comment the line below if you want to remove the comment and clear the registered variables. */ // session_destroy(); ?> You've hit this page times. "> Hit this page again

20 A Useful Bit of Code… foreach ($_SESSION as $sessVar => $value) $$sessVar = & $_SESSION[$sessVar];  Converts all session values to variables (that are aliased (attached) to session values)  Note that you can register ANY data type for a session and PHP will automatically encode and decode it in a session for you!  $myArray = array(1,2,3,4);  session_register('myArray');

21 What's A Shopping Cart Anyway?  Any information that keeps track of what a particular user wants from page to page, e.g.  Quantities array corresponding to products array  A single Orders array with functions to add, remove, get individual orders  …  Being tied to a specific user, this cries out for sessions!

22 So What's a Shopping Cart?  A shopping cart holds information about a particular user's choices and preferences  Must be able to uniquely identify user while the choices are being made and manipulated  Must tie a particular user’s data to a unique id  E.g. BSimpson chooses: 2 large gumballs 0 medium gumballs 5 small gumballs

23 Shopping Cart Designs  Need to maintain the following data for each unique user's purchase:  Quantity of large gumballs  Quantity of medium gumballs  Quantity of small gumballs  First, choose a data structure to store each users data. Some examples  Associative arrays: array('large'=>2, 'med'=>0, 'small'=>5);  indexed arrays (implicitly assumes an order of gumball sizes): array(2, 0, 5);  Array Orders: $anOrder[] = array('large' => 2); $anOrder[] = array('med' => 0); $anOrder[] = array('small' => 5);  Strings: 'large:2, med:0, small:5'

24 Shopping Cart Designs  Now need to tie the data to each user’s choices.  First, must have unique IDs for choices. Many ways to do this:  Use a unique user id  Use the IP address of the contacting system  Create a unique ID and pass it to the user's system as a cookie  Second, must tie a unique ID to the data structures and make this data persistent, e.g.  Associative arrays, keys are IDs  Individual file with name as ID

25 Using Cookies for Login and Session ID // got a userid cookie? If so, get the userid if(isset($_COOKIE["userid"])) { $username = $_COOKIE["userid"]; } // no userid cookie, so ask the user to login and send a cookie else { // define this function to ask for username and // pass and return username when valid $username = get_valid_login(); // send a cookie with username that expires in an hour setcookie("userid", $username, time()+3600 ); } // ok, logged in so start a session for username // use the unique username to identify this users session if ($username != '') session_id($username); session_start(); $_SESSION['logged_in'] = true; Be careful not to output anything after getting login!