_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.

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.
PHP and the Web: Session : 4. Predefined variables PHP provides a large number of predefined global variables to any script which it runs also called.
PHP (2) – Functions, Arrays, Databases, and sessions.
XP Tutorial 9 New Perspectives on JavaScript, Comprehensive1 Working with Cookies Managing Data in a Web Site Using JavaScript Cookies.
Chapter 10 Managing State Information PHP Programming with MySQL.
ASP.NET 2.0 Chapter 6 Securing the ASP.NET Application.
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.
Session Management A290/A590, Fall /25/2014.
1 The World Wide Web. 2  Web Fundamentals  Pages are defined by the Hypertext Markup Language (HTML) and contain text, graphics, audio, video and software.
Chapter 10 Maintaining State Information Using Cookies.
 A cookie is a piece of text that a Web server can store on a user's hard disk.  Cookie data is simply name-value pairs stored on your hard disk by.
1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a.
_______________________________________________________________________________________________________________ E-Commerce: Fundamentals and Applications1.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
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.
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.
IT533 Lectures Session Management in ASP.NET. Session Tracking 2 Personalization Personalization makes it possible for e-businesses to communicate effectively.
JavaScript, Fourth Edition
5 Chapter Five Web Servers. 5 Chapter Objectives Learn about the Microsoft Personal Web Server Software Learn how to improve Web site performance Learn.
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.
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
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
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.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
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.
Saving State on the WWW. The Issue  Connections on the WWW are stateless  Every time a link is followed is like the first time to the server — it has.
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
Fundamentals of Web DevelopmentRandy Connolly and Ricardo HoarFundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar Fundamentals of Web DevelopmentRandy.
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
How to maintain state in a stateless web Shirley Cohen
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)
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.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
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.
HTTP Transactions 1. 2 Client-Server Model 3 HTTP HyperText Transport Protocol Native protocol for WWW Sits on top of internet’s TCP/IP protocol HTTP.
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.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
Fundamentals of Web DevelopmentRandy Connolly and Ricardo HoarFundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar Fundamentals of Web DevelopmentRandy.
© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
Managing State Chapter 13.
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.
ITM 352 Cookies.
Maintaining State in PHP Part II - Sessions
Open Source Programming
What is Cookie? Cookie is small information stored in text file on user’s hard drive by web server. This information is later used by web browser to retrieve.
Maintaining State in PHP Part II - Sessions
Web Programming Language
Presentation transcript:

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the book authors, 2002 PHP Bible Chapter 24: Sessions, Cookies, and HTTP

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition2  Wiley and the book authors, 2002 Summary Why do you need sessions? How PHP sessions are implemented Cookies and their use Sending HTTP headers directly using PHP

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition3  Wiley and the book authors, 2002 What's a session? Informally, a session of Web browsing is a period of time during which a particular person, while sitting at a particular machine, views a number of different Web pages in his or her browser program and then calls it quits, either for the night or because the person in question actually has a life If you run a Web site that this person visits during that time, for your purposes the session runs from that person's first download of a page from your site through the last page downloaded Because the HTTP protocol is stateless, your Web server reacts independently to each individual request it receives and has no way to link requests together even if it is logging requests

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition4  Wiley and the book authors, 2002 Why should you care? If your Web site's only mission is to offer various pages to various users, we may not care at all where sessions begin and end On the other hand, there are a number of reasons why we might, in fact, care:  We want to customize our user's experiences as they move through the site, in a way that depends on which (or how many) pages they have already seen  We want to display advertisements to the user, but we do not want to display a given ad more than once per session  We want the session to accumulate information about users' actions as they progress – as in an adventure game's tracking of points and weapons accumulated, or an e-commerce site's shopping cart  We are interested in tracking how people navigate through our site in general – when they visit that interior page, is it because they bookmarked it, or did they get there all the way from the front page

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition5  Wiley and the book authors, 2002 "Home-grown" alternatives IP address  Web servers usually know either the host name or the IP address of the client that is requesting a page ( $_SERVER['REMOTE_ADDR'] )  If you get two requests in quick succession from the same IP address, your code can conclude that the same person followed a link or form from one of your site's pages to another  Cannot be considered unique, since many services may filter all requests from the users through a single IP address Hidden variables  You can check to see if a hidden variable is bound and assume it has been passed in and we are in the middle of a session  After generating a "session ID" and inserting it into a hidden form field, we can retrieve it later and use it to access a database where specific user information is stored Cookies  Cookies can also be utilized like hidden variables and can be retrieved from any page on your website

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition6  Wiley and the book authors, 2002 How sessions work in PHP Good session support takes care of the following two things: 1. Session tracking (detecting whether two separate script invocations are part of the same user session) 2. Storing information in association with a session PHP session tracking works by a combination of the hidden variables method and the cookie method Because of the advantages of cookies, PHP will use them when the user's browser supports them and, otherwise, will have recourse to stashing the session ID in a GET and POST argument Fortunately, the session functions themselves operate at a more abstract level and can take care of checking for cookie support

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition7  Wiley and the book authors, 2002 Making PHP aware of your session The first step in a script that uses the session feature is to let PHP know that a session may already be in progress so that it can hook up to it and recover any associated information This is accomplished by calling the function session_start(), which takes no arguments  Any call to session_register() causes an implicit initial call to session_start() The effect of session_start() depends on whether PHP can locate a previous session ID, as supplied either by HTTP arguments or in a cookie  If one is found, the values of any previously registered session variables are recovered  If one is not found, PHP assumes that we are in the first page of a new session and generates a new session ID

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition8  Wiley and the book authors, 2002 Propagating session variables Assuming that you've made a call to session_start() (as early in your script as possible), use the $_SESSION superglobal array as your suitcase for storing anything that you want to retrieve again from a later page in the same session  Assume that any other variable will be left behind when you leave the currently executing script and everything stored in the $_SESSION suitcase will be there when you arrive at the next page <?php session_start(); $temp_number = 45; $save_number = 19; // note: $save_number has nothing to do with $_SESSION['save_number'] // except for this assignment statement… $_SESSION['save_number'] = $save_number; ?> The receiving code can be as simple as the following example <?php session_start(); $save_number = $_SESSION['save_number']; print ('Saved number from previous PHP script is '.$save_number); ?>

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition9  Wiley and the book authors, 2002 Where is the data really stored There are two things that the session mechanism must hang onto: the session ID itself and any associated variable bindings The session ID is either stored as a cookie on the browser's machine, or it is incorporated into the GET/POST arguments submitted with page requests The contents of session variables are stored in special files on the server, one file per session ID  Doing this kind of storage requires the session code to serialize the data by turning it into a linear sequence of bytes that can be written to a file and read back to recreate the data  It's possible to configure PHP to store the contents of session variables in a server-side database, rather than in files

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition10  Wiley and the book authors, 2002 Sample session code This sample really has a dual purpose  Provide an example of a full, albeit short, script that successfully uses session functions  Provide a test script that you can use to make sure that you have session support and it is doing what you expect In this listing, we will perform the following tasks:  Initiate a session (or pick up an existing one)  Check for the existence of a pre-existing entry in $_SESSION (if it doesn't exist, we assume that the session is new)  Increment a counter that tracks how many times that the user has visited this page  Store the incremented counter back in $_SESSION  Provide a link back to the page itself, embedding the session ID as an argument if it is found which may allow session support to work even if cookie support isn't enabled on the client browser

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition11  Wiley and the book authors, 2002 Sample session code <?php session_start(); ?> Greetings Welcome to the Center for Content-free Hospitality <?php if (!IsSet($_SESSION['visit_count'])) { print ('Hello, you must have just arrived. Welcome '); $_SESSION['visit_count'] = 1; } else { $visit_count = $_SESSION['visit_count'] + 1; print ('Back again? That makes '.$visit_count.' times now'); $_SESSION['visit_count'] = $visit_count; } $self_url = $_SERVER['PHP_SELF']; $session_id = SID; if (IsSet($session_id) && $session_id) $href = "$self_url?session_id"; else $href = $self_url; print (' Visit us again sometime'); ?>

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition12  Wiley and the book authors, 2002 Cookies A cookie is a small piece of information that is retained on the client machine, either in the browser's application memory or as a small file written to the user's hard disk It contains a name/value pair  Setting a cookie means associating a value with a name and storing that pairing on the client side  Getting or reading a cookie means using the name to retrieve the value Typically, one Web server can store a maximum of 20 cookies per client In PHP, cookies are set using the setcookie() function, and cookies are read nearly automatically and show up in the $_COOKIE superglobal array

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition13  Wiley and the book authors, 2002 The setcookie() function There is just one cookie-related function, setcookie() The arguments are:  name: string – the name of your cookie (analogous to the name of a variable without the $)  value: string – The value you want to store in the cookie  If this argument is not supplied, the cookie named by the first argument is deleted  expire: int – Specifies when this cookie should expire  A value of 0 (default) means that it should last until the browser is closed. Any other integer is interpreted as an absolute time (as returned by the function mktime() ) when the cookie should expire  path: string – In the default case, any page within the Web root folder would see (and be able to set) this named cookie. Setting the path to a subdirectory allows distinguishing cookies that have the same name but are set by different subareas of the server  domain: string – In the default case, no check is made against the domain requested by the client. If this argument is nonempty, then the domain must match it  secure: int (0 or 1) – Defaults to 0. If the argument is 1, the cookie will only be sent over a secure connection CAUTION: calling setcookie() results in sending HTTP header information, which cannot be done after you have already sent some regular output

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition14  Wiley and the book authors, 2002 setcookie() examples setcookie('membername','timboy');  sets a cookie called membername with a value of timboy. Because thare are no arguments except name & value, the cookie will only persist until the current browser program is closed, it will be read on subsequent page requests from this browser to this server (regardless of the domain name or the directory of the page), and will be read regardless of whether or not the connection is secure setcookie('membername', 'troutgirl', time() + (60*60*24), '/', ' 1);  sets a cookie called membername with a value of troutgirl, overwriting the previous value of membername if it existed. The expiration time is set to 86,400 seconds (1 day) after the current time. It will be read regardless of where it is in the web directory heirarchy, but only by the host It will only be read or can be written across a secure connection

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition15  Wiley and the book authors, 2002 Other cookie operations Deleting cookies  To delete a cookie, simply call setcookie(cookie_name) without a second argument (e.g. setcookie('membername') ) Reading cookies  Cookies that have been successfully set in a browser or user's machine will automatically be read on the next request from that browser  As with session, get and post variables, you can access the value of the cookie through the $_COOKIE superglobal array (e.g. $_COOKIE['membername'] ) Once set, unlike the $_SESSION variables, you cannot read a cookie variable until the page is reloaded or another page is loaded

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition16  Wiley and the book authors, 2002 Sending HTTP headers The setcookie() call provides a wrapper around a particular usage of HTTP headers In addition, PHP offers the header() function which you can use to send raw, arbitrary HTTP headers You can also use this function to roll your own cookie function if you like, but you can also use it to take advantage of any kind of header-controlled functionality The syntax of header() just takes a single string argument, which is the header to be sent As with the setcookie function, header will not function if any text has already been sent to the browser

_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition17  Wiley and the book authors, 2002 Header examples Redirection  One useful kind of HTTP header is 'Locatin:', which can act as a redirector. Simply put a fully qualified URL after the 'Location:' string and the browser will start over again with the new address instead header('Location: HTTP authentication  If you want to ask the browser to ask the user for a username and password, you can use the WWW-Authenticate header header('WWW-Authenticate: Basic realm="PHP book"'); header('HTTP/ Unauthorized'); Using the header capability requires not only some knowledge of the HTTP protocols, but also some knowledge of the extent to which different browser version conform to them