Previous   -   Index   -   Next  >


Session Trolley


One way to maintain state in an extended dialogue with a user session is to store session data on the web server. There are many ways of storing data on a web server. Files and databases provide long-term, large-scale, persitent storage and PHP session variables provide convenient short-term, small-scale, volatile storage. PHP arrives with a plethora of session handling functions and strategies to simplify implementation of a session.

The group of data associated with a session is preserved until either it times out or a script explicitly terminates the session. Sound familiar?

The default timeout is a system configuration set in php.ini. PHP uses a timeout mechanism because there is no means for a server to know if a browser has terminated but still needs to avoid session variables accumulating unnecessarily.

Key to the implementation of a session is the generation of a unique identifier that allows a PHP script running on a web server to associate data with a web client. In this way any number of variables may be associated with a session ID.

Two methods are popularly used to propagate a session ID:

Cookies are the preferred method, but since they are not reliable (clients are not bound to accept them), we cannot depend upon them. The second method embeds the session ID directly into the URL as GET data. Clearly we could also use hidden form fields but that would require that each page is submitted and not just requested.

A PHP session uses cookies preferentially but if they are turned off the following script will automatically switch to using URL parameters.

See the documentation for chapter and verse on PHP session variables

Shopping Trolley example using session variables

shopping trolley
<?php
error_reporting(E_ERROR); // suppress warning messages
session_start();  // initialise session
header('Cache-control: private'); // allow the back button to function
?>
<?php echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/tr/xhtml1/DTD/xhtml1-strict.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb">
<head><title>PHP session example</title>
</head><body>
<h1>Shopping trolley</h1>
<h2>PHP session version</h2>
<form method="post" action="sessionTrolley.php?<?php echo SID ?>">
<p>Choose an item:</p>
<p><input type="radio" name="choice" value="camera"/> camera<br />
<input type="radio" name="choice" value="snorkel"/> snorkel<br />
<input type="radio" name="choice" value="octopus"/> octopus<br />
<input type="radio" name="choice" value="cuddly toy"/> cuddly toy<br /><br />
<input type="submit" name="submit" value="Add to the trolley"/>
<input type="submit" name="clear" value="Empty the trolley"/>
</p>
</form>
<?php
if ((!$_SESSION['trolley'] && !$_POST['choice']) || $_POST['clear']) {
   $_SESSION['trolley'] = "";
   echo '<p>Trolley currently empty</p>';
} else {
   if ( $_POST['choice'] ) {
      $_SESSION['trolley'] = $_SESSION['trolley'] . '<li>' . $_POST['choice'] . '</li>';
   }
   echo '<p>Trolley contains:</p><ul>';
   echo $_SESSION['trolley'] . '</ul>';
}
?>
<p><a href="sessionTrolley.html">Return to the PHP notes</a></p>
</body></html>

Things to notice about the Session Trolley

Starting a session

session_start();

Creates a session or resumes the current one based on the current session id that's being passed via a request, such as GET, POST, or COOKIE.

Because the session ID is preferentially handled by a cookie this function must be run before any other output so that it can handle the cookie.

Form action

<form method="post" action="sessionTrolley.php?<?php echo SID ?>">

The session ID is preferentially handled by a cookie. If the client does not accept a cookie then SID passes the session ID as get data with the URL.

SID is a constant with the value null if cookies are working otherwise it contains the string such as "PHPSESSID=79cec0b53bba8576631b8b477957fe1d".

So this PHP script only adds the session ID to the URL when cookies are not available. Observe how this script operates differently with and without cookies enabled in the browser.

This form uses HTTP POST method to send the form data to the PHP script. With cookies turned off the session ID becomes GET data.

This example will fail if there is other GET data - why? Clearly it could be easily refactored to allow either GET or POST form submission to work without cookies.

PHP requires transparent session ID's to be enabled (building PHP with --enable-trans-sid configured) by setting session.use_only_cookies to Off in php.ini (session.use_trans_sid may be zero or one).

Session variables

$_SESSION['trolley']

Any data in the $_SESSION array will be saved for the duration of the session.

You can store as many variables as you like in this associative array. This example uses only one session variable to store the entire trolley contents using <li> delimiters. You could just as easily save the trolley as an array of items within $_SESSION

The back button

header('Cache-control: private');

Prevents the browser 'Back' button from re-submitting the form. Allows the browser 'Back' button to operate slightly more intuitively. Although with this single PHP script the true state of the trolley is not shown when the back button is used.

If you want to see what happens without this directive then try this example


Previous   -   Index   -   Next  >

best viewed using Mozilla browsers
© k.mcmanus 2004
Valid XHTML 1.! . Valid CSS . WCAG priority 3 approved