Page 325 - Beginning PHP 5.3
P. 325
Chapter 10: Preserving State With Query Strings
H ow I t W orks
The script starts by calling session_start() to create a new session, or pick up an existing session if
one exists for this user. Then the script defines a Product class to hold the products in the store, and a
global $products array containing three Product objects, keyed by the numeric product IDs of the
products. (In a real - world scenario you ’ d probably store the products in a database.)
The code then initializes the user ’ s cart to an empty array if it doesn ’ t yet exist. The array is stored as
an element, cart , inside the $_SESSION superglobal. As with the $products array, this array will
hold the products selected by the user, keyed by product ID:
if ( !isset( $_SESSION[“cart”] ) ) $_SESSION[“cart”] = array();
The next few lines of code form the main decision logic of the script, calling addItem() if the user
chose to add an item to his cart, removeItem() if the user opted to remove a product, or
displayCart() if neither option was chosen by the user:
if ( isset( $_GET[“action”] ) and $_GET[“action”] == “addItem” ) {
addItem();
} elseif ( isset( $_GET[“action”] ) and $_GET[“action”] == “removeItem” ) {
removeItem();
} else {
displayCart();
}
The addItem() function looks for a productId field in the query string and, if present and valid,
adds the corresponding Product object to the user ’ s cart by inserting an array element into the
$_SESSION[ “ cart “ array, keyed by product ID. It then sends a Location: header to reload
]
the shopping cart:
function addItem() {
global $products;
if ( isset( $_GET[“productId”] ) and $_GET[“productId”] > = 1 and $_
GET[“productId”] < = 3 ) {
$productId = (int) $_GET[“productId”];
if ( !isset( $_SESSION[“cart”][$productId] ) ) {
$_SESSION[“cart”][$productId] = $products[$productId];
}
}
session_write_close();
header( “Location: shopping_cart.php” );
}
Note that the function calls the PHP function session_write_close() just before sending the
Location: header. This forces the data in the $_SESSION array to be written to the session file on the
server ’ s hard disk. Although PHP usually does this anyway when the script exits, it ’ s a good idea
to call session_write_close() before redirecting or reloading the browser to ensure that the
$_SESSION data is written to disk and available for the next browser request.
287
9/21/09 9:05:14 AM
c10.indd 287
c10.indd 287 9/21/09 9:05:14 AM