1 / 66

Session and Cookies

Session and Cookies. What is State Management?. Without State Management. With State Management. Login.php. Login.php. Please enter your logon information:. Please enter your logon information:. First Name. First Name. John. John. Last Name. Last Name. Chen. Chen. Web Server.

frayne
Download Presentation

Session and Cookies

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Session and Cookies

  2. What is State Management? Without State Management With State Management Login.php Login.php Please enter your logon information: Please enter your logon information: First Name First Name John John Last Name Last Name Chen Chen Web Server Submit Submit Web Server Greetings.php Greetings. php Hello Hello John Chen I forget who you are!!

  3. Types of State Management

  4. Server-Side State Management • Application state is a global storage mechanism accessible from all pages in the Web application • Session state is limited to the current browser session • Values are preserved through the use of application and session variables • Scalability • ASP.NET session is identified by the SessionID string Web Server Client Computer Application and Session variables SessionID

  5. Client-Side State Management • Uses cookies to maintain state • Persistent cookies • Temporary/ Non-persistent cookies • Less reliable than server-side state management options • User can delete cookies • Less secure than server-side state management options • Limited amount of information • Client-side restrictions on file sizes Web Server Client Computer Cookies

  6. While the configuration in this tutorial applies to ProdigyView, the concepts apply to normal cookies and sessions in php. You may use these concepts with these two php functions. session_set_cookie_params http://php.net/manual/en/function.session-set-cookie-params.php setcookie http://php.net/manual/en/function.setcookie.php Apply to Normal PHP

  7. You can insert the content of one file into another file before the server executes it, with the require() function. The require() function is used to create functions, headers, footers, or elements that will be reused on multiple pages. <?php require("header.htm"); ?> Server Side Includes

  8. Client-server connection is not permanent => Cannot be saved in program memory • There are many clients connecting simultaneously => Cannot be saved in file (you cannot identify clients as well sometimes) How to create variables storing values across php scripts’ calls? . . .

  9. Cookies • Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. • Sessions • Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. Different mechanisms of the same solution

  10. To maintain state means the ability to retain values of variables and to keep track of users who are logged into the system. What is meant by state?

  11.  HTTP is a stateless protocol. This means that each request is handled independently of all the other requests and it means that a server or a script cannot remember if a user has been there before.  However, knowing if a user has been there before is often required and therefore something known as cookies and sessions have been implemented.  Why Cookies and Sessions are Used?

  12. Cookies Sessions Passing [hidden] variables Methods for maintaining state

  13. Cookies is data the stored in the user’s browser. Unlike sessions, cookies will last if a user closes their browser. Cookies have a size limit set by the browser. Sensitive information should not be stored in the cookie. What is a Cookie Stored on user’s computer

  14. Cookies are simple text strings of the form of name=value which are stored persistently on the client’s machine. A URL is stored with each cookie and it is used by the browser to determine whether it should send the cookie to the web server. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. What is a cookie?

  15. setcookie(name [,value [,expire [,path [,domain [,secure]]]]]) name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed. path = Path on the server within and below which the cookie is available on. domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS connection only. Default false. Set a cookie

  16. The setcookie() function is used to create cookies. Note: The setcookie() function must appear BEFORE the <html> tag. setcookie(name, [value], [expire], [path], [domain], [secure]); This sets a cookie named "uname" - that expires after tenhours. <?php setcookie("uname", $name, time()+36000); ?> <html> <body> … How to Create a Cookie

  17. setcookie(‘name’,’Robert’) This command will set the cookie called name on the user’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).  Set a cookie examples

  18. setcookie(‘age’,’20’,time()+60*60*24*30) This command will set the cookie called age on the user’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days. Set a cookie - examples

  19. setcookie(‘gender’,’male’,0,’/’) This command will set the cookie called gender on the user’s PC containing the data male. It will be available within the entire domain that set it. It will expire and be deleted when the browser is closed. Set a cookie - examples

  20.  All cookie data is available through the superglobal $_COOKIE: $variable = $_COOKIE[‘cookie_name’] or $variable = $HTTP_COOKIE_VARS[‘cookie_name’]; e.g. $age = $_COOKIE[‘age’] Read cookie data

  21. To access a cookie you just refer to the cookie name as a variable or use $_COOKIE array • Tip: Use the isset() function to find out if a cookie has been set. <html> <body> <?php if (isset($uname)) echo "Welcome " . $uname . "!<br />"; else echo "You are not logged in!<br />"; ?> </body> </html> How to Retrieve a Cookie Value

  22. <?php $count++; setCookie(“count”, $count); ?> Welcome! You’ve seen this site <?php print($count . ($count == 1 ? “ time!” : “ times!”)); ?> Cookie Example

  23.  To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past… setcookie(‘cookie_name’,’’,time()-6000)  Note that theoretically any number taken away from the time() function should do, but due to variations in local computer times, it is advisable to use a day or two. Delete a cookie

  24. -> Values of the text typed in user form is passed to other HTML and/or server side script is called parameter passing. -> A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application.[1] -> Maintenance of user's state during session(e.g.login to logout) is called a Session Tracking. What is Parameter Passing & Session Tracking?

  25. Visible form parameters • Hidden form parameters • Cookies • Session • URL Rewriting Ways

  26. Methods of passing parameters with <form> • GET (smaller data i.e.1024 bytes) • POST(bigger data, as well as file upload) • PHP uses predefined variables • $_GET['varname'] • $_POST['varname'] Parameter Passing with <Form>

  27. PHP provides a large number of predefined variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers to all scripts. • Superglobals — Superglobals are built-in variables that are always available in all scopes • $GLOBALS — References all variables available in global scope • $_SERVER — Server and execution environment information • $_SERVER — Server and execution environment information • $_GET — HTTP GET variables • $_POST — HTTP POST variables • $_FILES — HTTP File Upload variables Predefined Variables[2]

  28. $_REQUEST — HTTP Request variables • $_SESSION — Session variables • $_ENV — Environment variables • $_COOKIE — HTTP Cookies • $php_errormsg — The previous error message • $HTTP_RAW_POST_DATA — Raw POST data • $http_response_header — HTTP response headers • $argc — The number of arguments passed to script • $argv — Array of arguments passed to script List of predefined variables [2]...

  29. Values of predefined variables can be seen with <?php phpinfo() ?> The values of Predefined Variables

  30. The session support allows you to register arbitrary numbers of variables to be preserved across requests. A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. What is a Session?

  31. Sessions are just like cookies, except they store the user’s data on the web server. Every request has a unique session id. Sessions are more reliable than cookies. Sessions

  32. Sessions is information that relates to a user and is stored on the server. A session will no longer exist once the browser closes. Sessions do not have a size limit. Sensitive information should be stored in the session. What is a Session User retrieves session information User saves session information

  33. The session_start() function is used to create cookies. <?php session_start(); ?> How to Create a Session

  34. Register Session variable • session_register('var1','var2',...);// will also create a session • PS:Session variable will be created on using even if you will not register it! • Use it <?php session_start(); if(!isset($_SESSION['count'])) $_SESSION['count'] = 0; else $_SESSION['count']++; ?> How to Retrieve a Session Value

  35. ?php // start the session session_start(); // Get the user's input from the form$name = $_POST['name']; // Register session key with the value $_SESSION['name'] = $name; ?> Session Example

  36. One of the standard examples used to demonstrate how a session works is the hit counter application. • The example of coding: <?php// initialize a session session_start(); // increment a session counter $_SESSION['counter']++; // print value echo "You have viewed this page " . $_SESSION['counter'] . " times"; ?> • With above code, the counter will increases by 1 on each subsequent page load. • If two browser windows are open, and request the same page in each one, PHP will maintain and increment individual session counters for each browser instance. SESSION

  37. In this example:- • Required to log in. • Then stored the login name and session start time as two session variables. • This information is used to display the total number of minutes the session has been active. Example 1

  38. <?php // initialize a session session_start(); ?> <html> <head></head> <body> <?php if (!isset($_SESSION['name']) && !isset($_POST['name'])) { // if no data, print the form ?>     <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">         <input type="text" name="name">         <input type="submit" name="submit" value="Enter your name">     </form> <?php } else if (!isset($_SESSION['name']) && isset($_POST['name'])) { // if a session does not exist but the form has been submitted     // check to see if the form has all required values     // create a new session if (!empty($_POST['name'])) { $_SESSION['name'] = $_POST['name']; $_SESSION['start'] = time();         echo "Welcome, " . $_POST['name'] . ". A new session has been activated for you. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page.";     }     else {         echo "ERROR: Please enter your name!";     } } else if (isset($_SESSION['name'])) { // if a previous session exists     // calculate elapsed time since session start and now echo "Welcome back, " . $_SESSION['name'] . ". This session was activated " . round((time() - $_SESSION['start']) / 60) . " minute(s) ago. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page."; } ?> </body> </html>

  39. The session start time is recorded in $_SESSION['start'] with the time() function. Then, the value stored in $_SESSION['start'] is compared with the most current value of time() to calculate and display an (approximate) display of elapsed time. The call to session_start() must appear first, before any output is generated by the script. This is because the PHP session handler internally uses in-memory cookies to store session data, and the cookie creation headers must be transmitted to the client browser before any output. Continue…

  40. Every session has a unique session ID – used by PHP to keep track of different clients. • This session ID is a long alphanumeric string, which is automatically passed by PHP from page to page so that the continuity of the session is maintained. • Use the session_id() function, as in this simple example: <?php // initialize a session session_start(); // print session ID echo "I'm tracking you with session ID " . session_id(); ?> Example 2

  41. When the user shuts down the client browser and destroys the session, the $_SESSION array will be flushed of all session variables. • A session can also explicitly be destroy. • For example, when a user logs out - by calling the session_destroy() function. • Consider the given example below:- <?php // initialize a session session_start(); // then destroy it session_destroy(); ?> • Before calling a session_destroy() to destroy a session, session_start() is called first to recreate it. • $_SESSION is a superglobal – can use it inside and outside functions without needing to declare it as global first. Example 3

  42. PHP offers a single function for cookie manipulation – setcookie(). • This function allows a read and write of cookie files. <?php if (!isset($_COOKIE['visited'])) { // if a cookie does not exist     // set it setcookie("visited", "1", mktime()+86400, "/") or die("Could not set cookie");     echo "This is your first visit here today."; } else { // if a cookie already exists echo "Nice to see you again, old friend!"; } ?> Cookies

  43. The setcookie() function accepts six arguments: • name: the name of the cookie • value: the value of the cookie • expires: the date and time at which the cookie expires • path: the top-level directory on the domain from which cookie data can be accessed • domain: the domain for which the cookie is valid • secure: a Boolean flag indicating whether the cookie should be transmitted only over a secure HTTP connection • Cookie values are automatically sent to PHP from the client. • Then, converted to key-value pairs in the $_COOKIE variable, a superglobal array similar to $_SESSION. • Values can be retrieved using standard associative array notation. Continue…

  44. <?php if (!isset($_POST['email'])) { // if form has not been submitted     // display form     // if cookie already exists, pre-fill form field with cookie value ?>     <html>     <head></head>     <body>     <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">         Enter your email address: <input type="text" name="email" value="<?php echo $_COOKIE['email']; ?>">         <input type="submit" name="submit"> <?php // also calculate the time since the last submission if ($_COOKIE['lastsave']) { $days = round((time() - $_COOKIE['lastsave']) / 86400);             echo "<br /> $days day(s) since last submission";         } ?>     </form>     </body>     </html> <?php } Form and Function

  45. else { // if form has been submitted     // set cookies with form value and timestamp     // both cookies expire after 30 days if (!empty($_POST['email'])) { setcookie("email", $_POST['email'], mktime()+(86400*30), "/"); setcookie("lastsave", time(), mktime()+(86400*30), "/");         echo "Your email address has been recorded.";     }     else {         echo "ERROR: Please enter your email address!";     } } ?> </body> </html> Continue…

  46. The value entered into the form is stored as a cookie called email. It will automatically retrieved to pre-fill the form field on all subsequent requests. The time at which the data was entered is stored as a second cookie, and used to calculate the time elapsed between successive entries. Continue…

  47. Session Tracking is done with As HTTP is stateless protocol Session Tracking must be maintained by programmers with following ways: Hidden form parameters Cookies Session URL Rewriting

  48. Hidden Parameter Passing Parameter is passed from 1 page to other which is not visible from user. <input type=hidden name=”username” value=”amichoksi”> Can be retrieved in PHP by $_GET[“username”] $_POST[“username”]

  49. Cookies [2] Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. Set Cookie bool setcookie ( string $name string $value , int $expire=0 , string $path , string $domain , bool $secure=false , bool $httponly=false) setcookie(“username”,”ami”,time()+300); Read Cookie $_COOKIE['name']

  50. Session Functions [2]

More Related