CHAPTER 10

download CHAPTER 10

If you can't read please download the document

description

CHAPTER 10. Managing State Information. Objectives. Learn about state information Use hidden form fields to save state information Use query strings to save state information Use cookies to save state information Use sessions to save state information. Understanding State Information. - PowerPoint PPT Presentation

Transcript of CHAPTER 10

  • CHAPTER 10Managing State Information

    PHP Programming with MySQL

  • ObjectivesLearn about state informationUse hidden form fields to save state informationUse query strings to save state informationUse cookies to save state informationUse sessions to save state information

    PHP Programming with MySQL

  • Understanding State InformationInformation about individual visits to a Web site is called state informationHTTP was originally designed to be stateless Web browsers store no persistent data about a visit to a Web siteMaintaining state means to store persistent information about Web site visits with hidden form fields, query strings, cookies, and sessions

    PHP Programming with MySQL

  • Understanding State InformationCustomize individual Web pages based on user preferencesTemporarily store information for a user as a browser navigates within a multipart formAllow a user to create bookmarks for returning to specific locations within a Web siteProvide shopping carts that store order information

    PHP Programming with MySQL

  • Understanding State InformationStore user IDs and passwordsUse counters to keep track of how many times a user has visited a siteThe four tools for maintaining state information with PHP are:Hidden form fieldsQuery strings CookiesSessions

    PHP Programming with MySQL

  • Understanding State InformationFigure 10-1 Skyward Aviation Frequent Flyer Web site page flow

    PHP Programming with MySQL

  • Understanding State InformationFigure 10-2 Registration/Log In Web page

    PHP Programming with MySQL

  • Understanding State InformationFigure 10-3 Frequent Flyer Club home page

    PHP Programming with MySQL

  • Understanding State InformationFigure 10-4 Frequent Flyer Registration Web page

    PHP Programming with MySQL

  • Using Hidden Form Fields to Save State InformationCreate hidden form fields with the elementHidden form fields temporarily store data that needs to be sent to a server that a user does not need to seeExamples include the result of a calculationThe syntax for creating hidden form fields is:

    PHP Programming with MySQL

  • Using Hidden Form Fields to Save State InformationHidden form field attributes are name and valueWhen submitting a form to a PHP script, access the values submitted from the form with the $_GET[] and $_POST[] autoglobalsTo pass form values from one PHP script to another PHP script, store the values in hidden form fields

    PHP Programming with MySQL

  • Using Hidden Form Fields to Save State Information

  • Using Query Strings to Save State InformationA query string is a set of name=value pairs appended to a target URLConsists of a single text string containing one or more pieces of informationAdd a question mark (?) immediately after a URL to pass information from one Web page to another using a query stringFollowed by the query string containing the information to preserve in name=value pairs

    PHP Programming with MySQL

  • Using Query Strings to Save State InformationSeparate individual name=value pairs within the query string using ampersands (&)A question mark (?) and a query string are automatically appended to the URL of a server-side script for any forms that are submitted with the GET methodLink Text

    PHP Programming with MySQL

  • Using Query Strings to Save State Informationecho "{$_GET['firstName']} {$_GET['lastName']} is a {$_GET['occupation']}. ";

    Figure 10-7 Output of the contents of a query string

    PHP Programming with MySQL

  • Using Cookies to Save State InformationQuery strings do not permanently maintain state informationAfter a Web page that reads a query string closes, the query string is lostTo store state information beyond the current Web page session, Netscape created cookiesCookies, or magic cookies, are small pieces of information about a user that are stored by a Web server in text files on the users computer

    PHP Programming with MySQL

  • Using Cookies to Save State InformationTemporary cookies remain available only for the current browser sessionPersistent cookies remain available beyond the current browser session and are stored in a text file on a client computerEach individual server or domain can store only 20 cookies on a users computerTotal cookies per browser cannot exceed 300 The largest cookie size is 4 kilobytes

    PHP Programming with MySQL

  • Creating CookiesThe syntax for the setcookie() function is: setcookie(name [,value ,expires, path, domain, secure])You must pass each of the arguments in the order specified in the syntaxTo skip the value, path, and domain arguments, specify an empty string as the argument valueTo skip the expires and secure arguments, specify 0 as the argument value

    PHP Programming with MySQL

  • Creating CookiesCall the setcookie() function before sending the Web browser any output, including white space, HTML elements, or output from the echo() or print() statementsUsers can choose whether to accept cookies that a script attempts to write to their systemA value of true is returned even if a user rejects the cookie

    PHP Programming with MySQL

  • Creating CookiesCookies cannot include semicolons or other special characters, such as commas or spaces, that are transmitted between Web browsers and Web servers using HTTPCookies can include special characters when created with PHP since encoding converts special characters in a text string to their corresponding hexadecimal ASCII value

    PHP Programming with MySQL

  • The name and value ArgumentsCookies created with only the name and value arguments of the setcookie() function are temporary cookies because they are available for only the current browser session

    Skyward Aviation...

    PHP Programming with MySQL

  • The name and value ArgumentsThe setcookie() function can be called multiple times to create additional cookies as long as the setcookie() statements come before any other output on a Web pagesetcookie("firstName", "Don");setcookie("lastName", "Gosselin");setcookie("occupation", "writer");

    PHP Programming with MySQL

  • The expires ArgumentThe expires argument determines how long a cookie can remain on a client system before it is deletedCookies created without an expires argument are available for only the current browser sessionTo specify a cookies expiration time, use PHPs time() functionsetcookie(firstName, Don, time()+3600);

    PHP Programming with MySQL

  • The path ArgumentThe path argument determines the availability of a cookie to other Web pages on a serverUsing the path argument allows cookies to be shared across a serverA cookie is available to all Web pages in a specified path as well as all subdirectories in the specified pathsetcookie(firstName, Don, time()+3600, /marketing/);setcookie(firstName, Don, time()+3600, /);

    PHP Programming with MySQL

  • The domain ArgumentThe domain argument is used for sharing cookies across multiple servers in the same domainCookies cannot be shared outside of a domainsetcookie(firstName, Don, time()+3600, /, .gosselin.com);

    PHP Programming with MySQL

  • The secure ArgumentThe secure argument indicates that a cookie can only be transmitted across a secure Internet connection using HTTPS or another security protocolTo use this argument, assign a value of 1 (for true) or 0 (for false) as the last argument of the setcookie() functionsetcookie(firstName, Don, time()+3600, /, .gosselin.com, 1);

    PHP Programming with MySQL

  • Reading CookiesCookies that are available to the current Web page are automatically assigned to the $_COOKIE autoglobalAccess each cookie by using the cookie name as a key in the associative $_COOKIE[] arrayecho $_COOKIE['firstName'];Newly created cookies are not available until after the current Web page is reloaded

    PHP Programming with MySQL

  • Reading CookiesTo ensure that a cookie is set before you attempt to use it, use the isset() functionsetcookie("firstName", "Don");setcookie("lastName", "Gosselin");setcookie("occupation", "writer");if (isset($_COOKIE['firstName']) && isset($_COOKIE['lastName']) && isset($_COOKIE['occupation'])) echo "{$_COOKIE['firstName']} {$_COOKIE['lastName']} is a {$_COOKIE['occupation']}.";

    PHP Programming with MySQL

  • Reading CookiesUse multidimensional array syntax to read each cookie valuesetcookie("professional[0]", "Don");setcookie("professional[1]", "Gosselin");setcookie("professional[2]", "writer");if (isset($_COOKIE['professional'])) echo "{$_COOKIE['professional'][0]} {$_COOKIE['professional'][1]} is a {$_COOKIE['professional'][2]}.";

    PHP Programming with MySQL

  • Deleting CookiesTo delete a persistent cookie before the time assigned to the expires argument elapses, assign a new expiration value that is sometime in the past Do this by subtracting any number of seconds from the time() functionsetcookie("firstName", "", time()-3600);setcookie("lastName", "", time()-3600);setcookie("occupation", "", time()-3600);

    PHP Programming with MySQL

  • Using Sessions to Save State InformationSpyware gathers user information from a local computer for marketing and advertising purposes without the users knowledgeA session refers to a period of activity when a PHP script stores state information on a Web serverSessions allow you to maintain state information even when clients disable cookies in their Web browsers

    PHP Programming with MySQL

  • Starting a SessionThe session_start() function starts a new session or continues an existing oneThe session_start() function generates a unique session ID to identify the sessionA session ID is a random alphanumeric string that looks something like: 7f39d7dd020773f115d753c71290e11fThe session_start() function creates a text file on the Web server that is the same name as the session ID, preceded by sess_

    PHP Programming with MySQL

  • Starting a SessionSession ID text files are stored in the Web server directory specified by the session.save_path directive in your php.ini configuration fileThe session_start() function does not accept any functions, nor does it return a value that you can use in your script
  • Starting a SessionYou must call the session_start() function before you send the Web browser any output If a clients Web browser is configured to accept cookies, the session ID is assigned to a temporary cookie named PHPSESSIDPass the session ID as a query string or hidden form field to any Web pages that are called as part of the current session

    PHP Programming with MySQL

  • Starting a Session

  • Working with Session VariablesSession state information is stored in the $_SESSION autoglobalWhen the session_start() function is called, PHP either initializes a new $_SESSION autoglobal or retrieves any variables for the current session (based on the session ID) into the $_SESSION autoglobal

    PHP Programming with MySQL

  • Working with Session Variables

  • Working with Session VariablesUse the isset() function to ensure that a session variable is set before you attempt to use it

    PHP Programming with MySQL

  • Deleting a SessionTo delete a session manually, perform the following steps:1. Execute the session_start() function 2. Use the array() construct to reinitialize the $_SESSION autoglobal3. Use the session_destroy() function to delete the session

    PHP Programming with MySQL

  • Deleting a Session

    4. Modify the Registration/Log In page so it deletes any existing user sessions whenever a user opens it

    PHP Programming with MySQL

  • SummaryInformation about individual visits to a Web site is called state informationMaintaining state means to store persistent information about Web site visits with hidden form fields, query strings, cookies, and sessionsThe four tools for maintaining state information with PHP are: hidden form fields, query strings, cookies, and sessionsA query string is a set of name=value pairs appended to a target URL

    PHP Programming with MySQL

  • SummaryCookies, or magic cookies, are small pieces of information about a user that are stored by a Web server in text files on the users computerCookies cannot include semicolons or other special characters, such as commas or spaces, that are transmitted between Web browsers and Web servers using HTTP but can using PHPThe path argument determines the availability of a cookie to other Web pages on a server

    PHP Programming with MySQL

  • SummaryThe domain argument is used for sharing cookies across multiple servers in the same domainThe secure argument indicates that a cookie can only be transmitted across a secure Internet connection using HTTPS or another security protocolA session refers to a period of activity when a PHP script stores state information on a Web server

    PHP Programming with MySQL