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.

Listing 11.3 adds two variables into the $_SESSION superglobal: product1 and product2 (lines 3 and 4).

Listing 11.3. Storing Variables in a Session
 1: <?php 2: session_start(); 3: $_SESSION[product1] = "Sonic Screwdriver"; 4: $_SESSION[product2] = "HAL 2000"; 5: echo "The products have been registered."; 6: ?> 

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

Listing 11.4. Accessing Stored Session Variables
 1: <?php 2: session_start(); 3: echo "Your chosen products are:"; 4: echo "<ul><li>$_SESSION[product1] <li>$_SESSION[product2]</ul>"; 5: ?> 

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

Figure 11.1. Accessing stored session variables.


Although not a terribly interesting or useful example, the script does show how to access stored session variables. Behind the scenes, PHP writes information 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,

 echo session_save_path(); 

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

 sess_fa963e3e49186764b0218e82d050de7b sess_76cae8ac1231b11afa2c69935c11dd95 sess_bb50771a769c605ab77424d59c784ea0 

Opening the file that matches the session ID I was allocated when I first ran Listing 11.2, 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 lateras 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 11.3 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 11.5 creates a form that allows a user to choose multiple products. You will use the session variables to create a rudimentary shopping cart.

Listing 11.5. Adding an Array Variable to a Session Variable
  1: <?php  2: session_start();  3: ?>  4: <html>  5: <head>  6: <title>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:         $_SESSION[products] = serialize($products); 17:     } else { 18:         $_SESSION[products] = serialize($_POST[form_products]); 19:   } 20:    echo "<p>Your products have been registered!</p>"; 21: } 22: ?> 23: <form method="POST" action="<?php $_SERVER[PHP_SELF]; ?>"> 24: <P><strong>Select some products:</strong><br> 25: <select name="form_products[]" multiple size=3> 26: <option value="Sonic Screwdriver">Sonic Screwdriver</option> 27: <option value="Hal 2000">Hal 2000</option> 28: <option value="Tardis">Tardis</option> 29: <option value="ORAC">ORAC</option> 30: <option value="Transporter bracelet">Transporter bracelet</option> 31: </select> 32: <P><input type="submit" value="choose"></p> 33: </form> 34: <p><a href="session1.php">go to content page</a></p> 35: </body> 36: </html> 

We start or resume a session by calling session_start() on line 2. This will give us access to any previously set session variables. We begin an HTML form on line 23 and, on line 25, create a SELECT element named form_products[], which contains OPTION elements for a number of products.

By the Way

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 1315). We then add the $products array to the $_SESSION superglobal on line 16.

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 11.5, but in the meantime you can save the code in Listing 11.5 as arraysession.php.

Moving on to Listing 11.6, we see how to access the items stored in the session created in arraysession.php.

Listing 11.6. Accessing Session Variables
  1: <?php  2: session_start();  3: ?>  4: <html>  5: <head>  6: <title>Accessing session variables</title>  7: </head>  8: <body>  9: <h1> Content Page</h1> 10: <?php 11: if (isset($_SESSION[products])) { 12:    echo "<strong>Your cart:</strong><ol>"; 13:    foreach (unserialize($_SESSION[products]) as $p) { 14:        echo "<li>$p"; 15:    } 16:    echo "</ol>"; 17: } 18: ?> 19: <p><a href="arraysession.php">return to product choice page</a></p> 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 1315, printing each of the user's chosen items to the browser. An example is shown in Figure 11.2.

Figure 11.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 Listings 11.5 and 11.6 demonstrate the ease with which you can use session functions to access array variables set in other pages.



Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net