chapter 12
play

Chapter 12 COOKIES AND SESSIONS INTRO Unlike the unified single - PowerPoint PPT Presentation

Chapter 12 COOKIES AND SESSIONS INTRO Unlike the unified single process that is the typical desktop application, a web application consists of a series of disconnected HTTP requests to a web server where each request for a server page is


  1. Chapter 12 COOKIES AND SESSIONS

  2. INTRO Unlike the unified single process that is the typical desktop application, a web application consists of a series of disconnected HTTP requests to a web server where each request for a server page is essentially a request to run a separate program. The web server sees only requests. The HTTP protocol does not, without programming intervention, distinguish two requests by one source as different than two requests from two different sources.

  3. INTRO

  4. 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 requires data to be sent from one page to another • Tools to maintain state: • Query strings • Form fields • Cookies • Sessions

  5. THE OPTIONS 1) QUERY STRINGS 2) HIDDEN FORM FIELDS Example: Example: <a href="http:// <input type="hidden" … gallery.php?image=monk.jpg"> name="image" value="$image"> Creates $_GET variables that the next page can use Use $_GET or $_POST Storage is temporary Storage is also temporary This will be discussed later

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

  7. COOKIES Cookies are name/value pairs sent by a server to store information on the client's machine. Examples of cookies • user_id=87 • email=jsmith@hotmail.com • userName=jsmith • passwordCookie=opensesame • PHPSESSID=D1F15245171203E8670487F020544490 Cookies must be sent from the server to the client before any other HTML is sent.

  8. COOKIES Cookies aren’t harmful by themselves: • Cookies don’t transmit viruses or steal passwords • Contain plain text – not able to directly modify a user’s computer, generate spam, steal files, etc. • Misuse is generally from advertisers who want to track sites users have visited Typical uses: • To allow users to skip login and registration forms • To customize pages • To focus advertising (banner-ads)

  9. HOW COOKIES WORK • On the server, a web application creates a cookie and sends it to the browser. • On the client, the browser saves the cookie locally 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.

  10. HOW COOKIES ARE HANDLED

  11. THE SETCOOKIE() FUNCTION Cookies are sent via the setcookie() function: setcookie( name , value ); setcookie('name', 'Nicole'); The cookie as seen in Chrome's Developer Tools

  12. SETCOOKIE() OPTIONAL 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 called persistent cookies. • time in seconds since 1/1/70 (Unix epoch) • or relative to the present using time() setcookie ( name , value , time()+1800);

  13. SETCOOKIE() OPTIONAL 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)

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

  15. SETCOOKIE() OPTIONAL PARAMETERS setcookie( $name , [ $value , $expire , $path , $domain , $secure , $httponly] ) Other optional 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

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

  17. 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 with: $_COOKIE['userName'] but only from another page!

  18. DELETING A COOKIE Cookies will automatically expire: • when the user closes the browser • when the expiration date/time is met A script can manually delete cookies by: • resetting the value parameter to ' ' • setting an expiration date in the past

  19. MORE 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.

  20. VIEWING COOKIES ON YOUR MACHINE In Firefox: Options -> Privacy & Security -> Cookies & Site Data -> Manage Data In Chrome: Settings -> Privacy & Security -> Site Data -> Cookies and site data -> See all cookies and site data

  21. 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

  22. SESSIONS Once the session starts, the superglobal $_SESSION[ ] array can be used to store data on the server: $_SESSION['user'] = $userID; Or to retrieve data from the server: $first_name = $_SESSION['first_name'];

  23. 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 is no longer available.

  24. SESSIONS…UNLIKE COOKIES • Session variables are available as soon as they are enabled • A session variable can be assigned a value and then referred to from within the same script (without reloading the page.)

  25. 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 accesses the data in the text file

  26. 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.

  27. 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();

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

  29. 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

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

  31. THEN WHAT? • Once the Login is successful, go to a default page for logged in users: logged_in.php • What if a user gets to logged_in.php by typing the URL? • Check to see if there is an existing session with session data.

  32. SETTING COOKIES FOLLOWING SUCCESSFUL LOGIN if (….) { // Login successful // Set the cookies: setcookie ('user_id', $user_id); You select what cookies or session data you setcookie ('first_name', $first_name); want to store // Redirect: to logged_in.php page } In general, don't store a primary key in a cookie, because cookies can be changed.

Recommend


More recommend