O'Reilly logo

Web Database Applications with PHP, and MySQL by David Lane, Hugh E. Williams

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PHP Session Management

In Chapter 8 we showed how to build session-based applications using the PHP session management functions. Applications use these functions to initialize sessions and register session variables as shown in Example D-1. This simple script initializes a session and registers two session variables: count and start.

Example D-1. A 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 is not 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>
  <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>

By default, PHP manages sessions by storing session variables in files on disk and uses the session ID as part of the filename. The session management functions and file storage are discussed in more detail in Chapter 8.

PHP allows user-defined handlers to be written that change how sessions are managed. The handlers define how PHP starts and terminates sessions, stores and retrieves session variables, and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required