PHP

Using Session Variables

Variables need to be registered with the session_register( ) function that's used in a session. If a session has not been initialized, the session_register( ) function calls session_start( ) to open the session file. Variables can be registered-added to the session file-with the session_register( ) call as follows:

// Register the variable named "foo"
session_register("foo");
$foo = "bar";

Note that it is the name of the variable that is passed to the session_register( ) function, not the variable itself. Once registered, session variables are made persistent and are available to scripts that initialize the session. PHP tracks the values of session variables and saves their values to the session file: there is no need to explicitly save a session variable before a script ends. In the previous example, the variable $foo is automatically saved in the session store with its value bar.

Variables can be removed from a session with the session_unregister( ) function call; again, the name of the variable is passed as the argument, not the variable itself. A variable that is unregistered is no longer available to other scripts that initialize the session. However, the variable is still available to the rest of the script immediately after the session_unregister( ) function call.

Scripts that initialize a session have access to the session variables through the associative array $HTTP_SESSION_VARS, and PHP automatically initializes the named session variables if register_globals is enabled.

Example 8-2 shows a simple script that registers two variables: an integer $count, which is incremented each time the script is called, and $start, which is set to the current time from the library function time( ) when the session is first initialized. The script tests if the variable $count has been registered to determine if a new session has been created. If the variable $count has been registered already, the script increments its value.

Do not use the existence of $PHPSESSID as indicative of a new session, or as a method to access the session ID. The first time a script is called and the session is created, the PHPSESSID cookie may not be set. Only subsequent requests are guaranteed to contain the PHPSESSID cookie. PHP provides a session_id( ) function that returns the session ID for the initialized session.

The script shown in Example 8-2 displays both variables: $count shows how many times the script has been called, and time( ) - $start shows how many seconds the session has lasted.

Example 8-2. Simple PHP script that uses a session
<?php
  // Initialize a session. This call either creates
  // a new session or re-establishes an existing one.
  session_start(  );
  // If this is a new session, then the variable
  // $count will not be registered
  if (!session_is_registered("count"))
  {
    session_register("count");
    session_register("start");
    $count = 0;
    $start = time(  );
  }
  else
  {
    $count++;
  }
  $sessionId = session_id(  );
?>
<!DOCTYPE HTML PUBLIC
   "-//W3C//DTD HTML 4.0 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd" >
<html>
  <head><title>Sessions</title></head>
  <body>
    <p>This page points at a session
        (<?=$sessionId?>)
    <br>count = <?=$count?>.
    <br>start = <?=$start?>.
    <p>This session has lasted
      <?php
        $duration = time(  ) - $start;
    echo "$duration";
      ?>
      seconds.
  </body>
</html>

Session variables can be of the type Boolean, integer, double, string, object, or arrays of those variable types. Care must be taken when using object session variables, because PHP needs access to the class definitions of registered objects when initializing an existing session. If objects are to be stored as session variables, you should include class definitions for those objects in all scripts that initialize sessions, whether the scripts use the class or not. Objects and classes are described in Chapter 2.

PHP stores session variables in the session file by serializing the values. The serialized representation of a variable includes the name, the type, and the value as a stream of characters suitable for writing to a file. Here's an example of a file that was created when the script shown in Example 8-2 was run several times:

count|i:6;start|i:986096496;

A PHP developer need not worry how serialization occurs; PHP session management takes care of reading and writing session variables automatically.

by BrainBellupdated
Advertisement: