Working with Session Variables

Accessing a unique session. identifier in each of your PHP documents is only the start of session functionality. When a session is started, you can store any number of variables in the $_SESSION superglobal and then access them on any session-enabled page.


If you are using a pre-4.1.x version of PHP, the $_SESSION superglobal is not present, and session functionality is much different. If you cannot upgrade to the current version of PHP, read the PHP manual section on sessions, which includes notes for early releases.

Listing 16.2 adds two variables into the. $_SESSION superglobal: product1 and product2 (lines 10 and 11).

Listing 16.2 Storing Variables in a Session
  1: <?php
  2: session_start();
  3: ?>
  4: <html>
  5: <head>
  6: <title>Listing 16.2 Storing variables in a session</title>
  7: </head>
  8: <body>
  9: <?php
 10: $_SESSION[product1] = "Sonic Screwdriver";
 11: $_SESSION[product2] = "HAL 2000";
 12: print "The products have been registered.";
 13: ?>
 14: </body>
 15: </html>

The magic in Listing 16.2 will not become apparent until the user moves to a new page. Listing 16.3 creates. a separate PHP script that accesses the variables stored in the $_SESSION superglobal in Listing 16.2.

Listing 16.3 Accessing Stored Session Variables
  1: <?php
  2: session_start();
  3: ?>
  4: <html>
  5: <head>
  6: <title>Listing 16.3 Accessing stored session variables</title>
  7: </head>
  8: <body>
  9: <?php
 10: print "Your chosen products are:\n\n";
 11: print "<ul><li>$_SESSION[product1]\n<li>$_SESSION[product2]\n</ul>\n";
 12: ?>
 13: </body>
 14: </html>

Figure 16.1 shows the output from Listing 16.3. As you can see, we have access to the $_SESSION[product1] and $_SESSION[product2] variables in an entirely new page.

Figure 16.1. Accessing stored session variables.


So how does the magic work? Behind the scenes, PHP 4 writes to a temporary file. You can find out where this file is being written on your system by using the session_save_path() function. This function optionally accepts a path to a directory and then writes all session files to it. If you pass it no arguments, it returns a string representing the current directory to which session files are saved. On my system,

print session_save_path();

prints /tmp. A glance at my /tmp directory reveals a number of files with names like the following:


Opening the file that matches the session ID I was allocated when I first ran Listing 16.1, I can see how the registered variables have been stored:

product1|s:17:"Sonic Screwdriver";product2|s:8:"HAL 2000";

When a value is placed in the $_SESSION superglobal, PHP writes the variable name and value to a file. This information can be read and the variables resurrected later?as you have already seen. After you add a variable to the $_SESSION superglobal, you can still change its value at any time during the execution of your script, but the altered value won't be reflected in the global setting until you reassign the variable to the $_SESSION superglobal.

The example in Listing 16.2 demonstrates the process of adding variables to the $_SESSION superglobal. This example is not very flexible, however. Ideally, you should be able to register a varying number of values. You might want to let users pick products from a list, for example. In this case, you can use the serialize() function to store an array in your session.

Listing 16.4 creates a form that allows a user to choose multiple products. You should then be able to use session variables to create a rudimentary shopping cart.

Listing 16.4 Adding an Array Variable to a Session Variable
  1: <?php
  2: session_start();
  3: ?>
  4: <html>
  5: <head>
  6: <title>Listing 16.4 Storing an array with a session</title>
  7: </head>
  8: <body>
  9: <h1>Product Choice Page</h1>
 10: <?php
 11: if (isset($_POST[form_products])) {
 12:     if (!empty($_SESSION[products])) {
 13:         $products = array_unique(
 14:        array_merge(unserialize($_SESSION[products]),
 15:         $_POST[form_products]));
 16:    }
 17: $_SESSION[products] = serialize($products);
 18: print "<p>Your products have been registered!</p>";
 19: }
 20: ?>
 21: <form method="POST" action="<?php $_SERVER[PHP_SELF] ?>">
 22: <P>Select some products:<br>
 23: <select name="form_products[]" multiple size=3>
 24: <option>Sonic Screwdriver</option>
 25: <option>Hal 2000</option>
 26: <option>Tardis</option>
 27: <option>ORAC</option>
 28: <option>Transporter bracelet</option>
 29: </select>
 30: <br><br>
 31: <input type="submit" value="choose">
 32: </form>
 33: <br><br>
 34: <a href="listing16.5.php">content page</a>
 35: </body>
 36: </html>

We start or resume a session by calling session_start() on line 2. This should give us access to any previously set session variables. We begin an HTML form on line 21 and, on line 23, create a SELECT element named form_products[], which contains OPTION elements for a number of products. Remember that HTML form elements that allow multiple selections should have square brackets appended to the value of their NAME arguments. This makes the user's choices available in an array.

Within the block of PHP code beginning on line 10, we test for the presence of the $_POST[form_products] array (line 11). If the variable is present, we can assume that the form has been submitted and information has already been stored in the $_SESSION superglobal. We then test for an array called $_SESSION[products] on line 12. If the array exists, it was populated on a previous visit to this script, so we merge it with the $_POST[form_products] array, extract the unique elements, and assign the result back to the $products array (lines 13?15). We then add the $products array to the $_SESSION superglobal on line 17.

Line 34 contains a link to another script, which we will use to demonstrate our access to the products the user has. chosen. We create this new script in Listing 16.5.

Listing 16.5 Accessing Session Variables
  1: <?php
  2: session_start();
  3: ?>
  4: <html>
  5: <head>
  6: <title>Listing 16.5 Accessing session variables</title>
  7: </head>
  8: <body>
  9: <h1> Content Page</h1>
 10: <?php
 11: if (isset($_SESSION[products])) {
 12:    print "<b>Your cart:</b><ol>\n";
 13:    foreach (unserialize($_SESSION[products]) as $p) {
 14:        print "<li>$p";
 15:    }
 16:    print "</ol>";
 17: }
 18: ?>
 19: <a href="listing16.4.php">Back to product choice page</a>
 20: </body>
 21: </html>

Once again, we use session_start() to resume the session on line 2. We test for the presence of the $_SESSION[products] variable on line 11. If it exists, we unserialize it and loop through it on lines 13?15, printing each of the user's chosen items to the browser. An example is shown in Figure 16.2.

Figure 16.2. Accessing an array of session variables.


For a real shopping cart program, of course, you would keep product details in a database and test user input, rather than blindly store and present it, but Listing 16.4 and 16.5 demonstrate the ease with which you can use session functions to access array variables set in other pages.

    Part III: Getting Involved with the Code