Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the."— Presentation transcript:

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

2 _______________________________________________________________________________________________________________ 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

3 _______________________________________________________________________________________________________________ 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

4 _______________________________________________________________________________________________________________ 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

5 _______________________________________________________________________________________________________________ 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

6 _______________________________________________________________________________________________________________ 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

7 _______________________________________________________________________________________________________________ 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

8 _______________________________________________________________________________________________________________ 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); ?>

9 _______________________________________________________________________________________________________________ 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

10 _______________________________________________________________________________________________________________ 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

11 _______________________________________________________________________________________________________________ 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'); ?>

12 _______________________________________________________________________________________________________________ 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

13 _______________________________________________________________________________________________________________ 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

14 _______________________________________________________________________________________________________________ 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), '/', 'www.troutworks.com', 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 www.troutworks.com. It will only be read or can be written across a secure connection

15 _______________________________________________________________________________________________________________ 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

16 _______________________________________________________________________________________________________________ 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

17 _______________________________________________________________________________________________________________ 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://siu.globaleyes.com'); 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/1.0 401 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


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

Similar presentations


Ads by Google