[ Team LiB ] Previous Section Next Section

Working with Session Variables

Accessing a unique identifier on each of your PHP documents is only the start of PHP's session functionality. You can set any number of variables as elements of the superglobal $_SESSION array. After these are set, they are available to future requests in the session.

Listing 20.2 registers two variables with a session (lines 10 and 11).

Listing 20.2 Registering Variables with a Session
 1: <?php
 2: session_start();
 3: ?>
 4: <!DOCTYPE html PUBLIC
 5:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 6:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 7: <html>
 8: <head>
 9: <title>Listing 20.2 Registering Variables with a Session</title>
10: </head>
11: <body>
12: <div>
13: <?php
14: $_SESSION['product1'] = "Sonic Screwdriver";
15: $_SESSION['product2'] = "HAL 2000";
16: print "The products have been registered";
17: ?>
18: </div>
19: </body>
20: </html>

The magic in Listing 20.2 will not become apparent until the user moves to a new page. Listing 20.3 creates a separate PHP script that accesses the variables registered in Listing 20.2 (line 11).

Listing 20.3 Accessing Session Variables
 1: <?php
 2: session_start();
 3: ?>
 4: <!DOCTYPE html PUBLIC
 5:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 6:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 7: <html>
 8: <head>
 9: <title>Listing 20.3 Accessing Session Variables</title>
10: </head>
11: <body>
12: <div>
13: <?php
14: print "Your chosen products are:\n\n";
15: ?>
16: <ul>
17: <li><?php print $_SESSION['product1'] ?></li>
18: <li><?php print $_SESSION['product2'] ?></li>
19: </ul>
20: </div>
21: </body>
22: </html>

Figure 20.1 shows the output from Listing 20.3. As you can see, you have access to the product1 and product2 elements of the $_SESSION array in an entirely new page.

Figure 20.1. Accessing session variables.

graphics/20fig01.gif

So, how does the magic work? Behind the scenes, PHP is writing to a temporary file. You can find out where this is being written on your system with the session_save_path() function, which optionally accepts a path to a directory and then writes all session files to this. 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:


sess_2638864e9216fee10fcb8a61db382909
sess_76cae8ac1231b11afa2c69935c11dd95
sess_bb50771a769c605ab77424d59c784ea0

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


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

When an element is added to the $_SESSION array, PHP writes the element name and value to a file. This can be read later, and the element resurrected.

After you have created a session element, you can amend it at will during the execution of your script, and the altered value is reflected in the session file.

The example in Listing 20.2 demonstrates the process of registering elements with a session. It 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. Luckily, $_SESSION elements do not have to be scalars. You can add arrays or even objects and their data is encoded and stored for you.

Listing 20.4 creates a form that enables a user to choose multiple products. You should then be able to use session elements to create a rudimentary shopping cart.

Listing 20.4 Registering an Array Variable with a Session
 1: <?php
 2: session_start();
 3:
 4: if ( empty( $_SESSION['products'] ) ) {
 5:   $_SESSION['products']=array();
 6: }
 7:
 8: if ( is_array( $_REQUEST['form_products'] ) ) {
 9:   $_SESSION['products'] = array_unique(
10:     array_merge( $_SESSION['products'],
11:           $_REQUEST['form_products'] )
12:   );
13: }
14: ?>
15: <!DOCTYPE html PUBLIC
16:   "-//W3C//DTD XHTML 1.0 Strict//EN"
17:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
18: <html>
19: <head>
20: <title>Listing 20.4 Registering an Array Element with a Session</title>
21: </head>
22: <body>
23: <div>
24: <h1>Product Choice Page</h1>
25: <form action="<?php print $_SERVER['PHP_SELF']?>" method="post">
26: <p>
27: <select name="form_products[]" multiple="multiple" size="3">
28: <option>Sonic Screwdriver</option>
29: <option>Hal 2000</option>
30: <option>Tardis</option>
31: <option>ORAC</option>
32: <option>Transporter bracelet</option>
33: </select>
34: </p>
35: <p>
36: <input type="submit" value="choose" />
37: </p>
38: </form>
39: <a href="listing20.5.php">A content page</a>
40: </div>
41: </body>
42: </html>

We begin an HTML form on line 25 and, on line 27, create a select element named form_products[], which contains option elements for several products. 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.

We start or resume a session with session_start() on line 2. This should give us access to any previously set session elements. We test the $_SESSION['products'] element on line 4, setting it as an empty array if it does not already exist. We then test the superglobal $_REQUEST array for the presence of the form_products array element (line 8). If the array is present, we can assume that the form has been submitted and go on to assign any new items to the $_SESSION['products'] array. We do this in a single statement, merging the $_REQUEST['form_products'] array with $_SESSION['products'] and assigning the unique elements back to $_SESSION['products'](lines 911). Note that in this example code, we do not check user input. In a real-world situation, we would not blindly assign user input to a session but would first check all input against an array of acceptable values.

At the end of Listing 20.4 (line 39), a link to another script is used to demonstrate our access to the products the user has chosen. We create this new script in Listing 20.5.

Listing 20.5 Accessing Session Variables
 1: <?php
 2: session_start();
 3: ?>
 4: <!DOCTYPE html PUBLIC
 5:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 6:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 7: <html>
 8: <head>
 9: <title>Listing 20.5 Accessing Session Elements</title>
10: </head>
11: <body>
12: <div>
13: <h1>A Content Page</h1>
14: <?php
15: if ( is_array( $_SESSION['products'] ) ) {
16:   print "<b>Your cart:</b><ol>\n";
17:   foreach ( $_SESSION['products'] as $p ) {
18:     print "<li>$p</li>";
19:   }
20:   print "</ol>";
21: }
22: ?>
23: <a href="listing20.4.php">Back to product choice page</a>
24: </div>
25: </body>
26: </html>

Again, we use session_start() to resume the session (line 2). We test for the presence of the products session element on line 15. If it exists, we loop through it on line 17, printing each of the user's chosen items to the browser.

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

    [ Team LiB ] Previous Section Next Section