O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

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

Managing Sessions

The Web was designed for browsing documents, where each request from a web browser to a web server is independent of every other interaction. To develop applications for the Web, additional logic is required so that different requests can be related. For example, this logic is required to allow users to log in, use the gift registry application, and log out when they’re finished. In PHP, the logic is provided by the sessions library.

Sessions allow variables to be stored on the server so the variables can be restored each time a user requests a script. Consider a short example:

<?php
  session_start(  );
          
  if (session_is_registered("count"))
  {       
     echo "Hello! You've visited {$count} times";  
     $count++;
  }       
  else    
  {
     echo "Welcome new user!";
     session_register("count");
     $count = 1;
  }
?>

When the user requests the script for the first time, a new session is created. Then, a variable $count is registered and stored on the web server with its associated value of 1. When the script is requested again, the variable is automatically restored by the PHP engine and the count incremented. For example, on the fifth request of the script the output is:

Hello! You've visited 5 times

With its default configuration, the sessions library relies on cookies. Cookies are strings that are passed back and forth between the web server and browser and are used in sessions to maintain a unique key. This key is used on the server to locate the variables associated with the session. If cookies are disabled ...

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