Page 177 - Open Soource Technologies 304.indd
P. 177
Open Source Technologies
Notes 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.
In example 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.
Example: 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.
Adding an Array Variable to a Session Variable
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Listing 10.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: $_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>
172 LOVELY PROFESSIONAL UNIVERSITY