Session techniques

  • Sessions allow us to keep track of variables from one scripted page to the next without having to carefully manage the sending of the variable from page to page
  • Sessions are treated as cookies in older browsers. But in IE6 and Mozilla, even if someone has 'do not accept cookies', the browser will still accept the session key, which is the critical variable that lets PHP access the server-side session cookie (in the server's tmp directory).
  • The politics of cookies You may have thought all cookies are good cookies, but it may not be true. Often what happens with advertising-sponsored sites is that they will write a cookie (client-side) for later use, to reactivate data that has been saved during a session. In this way, a demographic profile can be established about you. So cookies are a mechanism for keeping track of who you are and what you have done before on a web site. Where this becomes particularly questionable is when companies, such as DoubleClick begin tracking you for all of their clients (as they were reported to have been doing in the late 90s).
  • Nevertheless, sessions are very convenient for establishing persistent variables, and cookies can augment this persistence for good or ill.
  • Practically speaking, sessions are conveyed in the headers of each transmission to and from the browser, so you must use session_start() before you print any data from your .php script. If you want to set a persistent variable, you simply register the name of the variable in a global $_SESSION array, as for example $_SESSION["my_var_name"] = "something";
  • Examples of uses of sessions are things like shopping carts or keeping track of who's online, how long they've been browsing your site, and where they are currently browsing (a few persistent, regularly updated variables could enable a map of this information).

  • Authentication

  • Sessions are also useful for authentication.
  • Although there are other authentication techniques that involve pop-up dialog windows, sessions are a way of personalizing the login interface while still maintaining a lock mechanism on your content.
  • By establishing a 'loggedIn' session variable that is only set when a user has effectively passed a user/password test (using https if necessary), you can establish a way to tell whether someone is authorized to see your protected pages.
  • In this model, all pages need to include() the session_start() and checking code to make sure the 'loggedIn' variable is set to a suitable value. If not, users should be redirected using the header("Location: login.php"); technique to a login page.
  • If there are people writing HTML (.html) files for your site, and you cannot envision protecting each page using this .php solution, there are ways to establish zones in your website that are protected. See the server software documentation for authentication help.