PHP Sessions

A session is the time spent by a user browsing a particular website. The HTTP protocol that is used to retrieve web pages from a web server does not provide a mechanism for tracking the user's progress from one page to the next as the user navigates through a web site, or for storing any information about the user. Because of this, the HTTP protocol is said to be stateless (i.e. it does not store information about the state of the application with regard to a particular session). This obviously poses a problem for web applications such as online shopping carts that need to store information about the user, the pages they have visited, and the products they have selected. A PHP session solves the problem by allowing the application to store information like this on the server. The data is stored only as long as the user remains on the site. Once they leave, it is deleted automatically (any data that must be stored permanently should be written to a server-side database such as MySQL).

When a session is created, a unique Session ID is set up for the user that is subsequently made available to each page the user visits. The Session ID is a very long alphanumeric string value and is stored in a PHP system variable called PHPSESSID. The method used to pass the Session ID to each page the user visits depends on whether or not the user has cookies turned on. If they do, PHP passes the session ID to each page using cookies. Otherwise, the PHPSESSID variable can be passed to each page the user visits using the GET method. An arbitrary number of session variables can be declared and associated with the Session ID to allow information about the user and their activities to be temporarily stored on the server. The variables are stored in a file that has the same name as the Session ID, in a directory on the server that is identified by the session.save_path variable in the php.ini file. Each page the user visits can access the stored variables for the current session via an array variable called $_SESSION.


Starting a session

Before doing anything else, you need to start the session. The code to do this for a typical web page is shown below, and must appear before any HTML code. The code registers the session with the server and assigns the Session ID for the session. Note that this code should appear at the top of each page that is part of the web application. The session_start() function checks for an existing session. If one is not found, it creates a new session and gives it a Session ID.

<?php
  session_start();
?>

<html>

  <head>
    <title>Some web page</title>
  </head>

  <body>
    <!-- The page content goes here -->
  </body>
</html>


Storing a session variable

Information relating to the session can be stored in session variables using the $_SESSION associative array. In the example below, a simple counter variable is created for the session and is set to 1. In the root of your XAMPP server (on my computer, this would be X:\xampp\htdocs), create a file called "session01.php" and paste in the following code:

<?php
  session_start();
  $_SESSION['count'] = 1;
?>

<html>
  <head>
    <title>Some web page</title>
  </head>
  <body>
    <?php
      $_SESSION['count'] = 1;
      echo "Counter value = ".$_SESSION['count'];
    ?>
  </body>
</html>

The output from "session01.php" is shown below.


The output from session01.php

The output from session01.php



The isset() function

It is good practice to check whether a variable exists and has been assigned a value before attempting to read or modify its value. This can be achieved using the isset() function which accepts a session variable name as its argument and returns true if the variable has been set (given a value) and false otherwise. We can modify the previous coding example to use the isset() function to check whether the count variable exists and has been set. If it has, the code will increment the value of count. If not, the count variable will be created and set to 1. Create a new file called "session02.php" in the root of your XAMPP server and paste in the following code:

<?php
  session_start();
  if(isset($_SESSION['count']))
    $_SESSION['count'] = $_SESSION['count'] + 1;
  else
    $_SESSION['count'] = 1;
?>
<html>
  <head>
    <title>Some web page</title>
  </head>
  <body>
    <?php
      echo "Counter value = ".$_SESSION['count'];
    ?>
  </body>
</html>

The output from "session02.php" will be similar to that for the previous example, except that if you refresh the page several times, you should see the value of count increase by one on each occasion.


The unset() function

Although session data is transient in nature and will be deleted when the session terminates, you may wish to clear the contents of a particular session variable under certain circumstances. For example, if the user of an online shopping application decides to cancel their current order altogether and browse the site further before making any decisions, the variables that contain information about the contents of their shopping cart can be cleared (unset) using the unset() function. We will now modify the previous code example to demonstrate this feature by clearing the count variable when its value reaches 10. Create a new file called "session03.php" in the root of your XAMPP server and paste in the following code:

<?php
  session_start();
  if(isset($_SESSION['count']))
  {
    $_SESSION['count'] = $_SESSION['count'] + 1;
      if($_SESSION['count'] > 10)
        unset($_SESSION['count']);
  }
  else
    $_SESSION['count'] = 1;
?>

<html>
  <head>
    <title>Some web page</title>
  </head>
  <body>
    <?php
      if(isset($_SESSION['count']))
        echo "Counter value = ".$_SESSION['count'];
      else
        echo "The counter does not currently have a value!";
    ?>
  </body>
</html>

The output from "session03.php" will be similar to that for the previous example. The first time it runs, you will see the value of count displayed as 1. If you refresh the page repeatedly, you will see the value of count increasing by one each time as happened previously. Once you have seen the value of count displayed as 10, however, the next refresh will produce a page that displays the message "The counter does not currently have a value!" The next refresh will display the page in the same state in which it appeared the first time you opened it, i.e. with the value of count displayed as 1.


The session_destroy() function

As well as clearing a session variable, it is possible to clear the entire session, including its Session ID, by calling the rather dramatically named session_destroy() function. Although a session is automatically terminated and all data pertaining thereto is deleted from the server when the user leaves the web application, you could use this function to explicitly terminate a session and remove all stored data. The following code fragment illustrates the use of this function:

<?php
  session_destroy();
?>