DekGenius.com
Previous Section  < Day Day Up >  Next Section

8.3 Storing and Retrieving Information

Session data is stored in the $_SESSION auto-global array. Read and change elements of that array to manipulate the session data. Example 8-9 shows a page counter that uses the $_SESSION array to keep track of how many times a user has looked at the page.

Example 8-9. Counting page accesses with a session
session_start( );

$_SESSION['count'] = $_SESSION['count'] + 1;

print "You've looked at this page " . $_SESSION['count'] . ' times.';

The first time a user accesses the page in Example 8-9, no PHPSESSID cookie is sent by the user's web client to the server. The session_start( ) function creates a new session for the user and sends a PHPSESSID cookie with the new session ID in it. When the session is created, the $_SESSION array starts out empty. So, $_SESSION['count'] = $_SESSION['count'] + 1 sets $_SESSION['count'] to 1. The print statement outputs:

You've looked at this page 1 times.

At the end of the request, the information in $_SESSION is saved into a file on the web server associated with the appropriate session ID.

The next time the user accesses the page, the web client sends the PHPSESSID cookie. The session_start( ) function sees the session ID in the cookie and loads the file that contains the saved session information associated with that session ID. In this case, that saved information just says that $_SESSION['count'] is 1. Next, $_SESSION['count'] is incremented to 2 and You've looked at this page 2 times. is printed. Again, at the end of the request, the contents of $_SESSION (now with $_SESSION['count'] equal to 2) are saved to a file.

The PHP interpreter keeps track of the contents of $_SESSION separately for each session ID. When your program is running, $_SESSION contains the saved data for one session only—the active session corresponding to the ID that was sent in the PHPSESSID cookie. Each user's PHPSESSID cookie has a different value.

As long as you call session_start( ) at the top of a page (or if session.auto_start is on), you have access to a user's session data in your page. The $_SESSION array is a way of sharing information between pages.

Example 8-10 is a complete program that displays a form in which a user picks a dish and a quantity. That dish and quantity are added to the session variable order.

Example 8-10. Saving form data in a session
<?php
require 'formhelpers.php';

session_start( );

$main_dishes = array('cuke' => 'Braised Sea Cucumber',
                     'stomach' => "Sauteed Pig's Stomach",
                     'tripe' => 'Sauteed Tripe with Wine Sauce',
                     'taro' => 'Stewed Pork with Taro',
                     'giblets' => 'Baked Giblets with Salt', 
                     'abalone' => 'Abalone with Marrow and Duck Feet');

if ($_POST['_submit_check']) {
    if ($form_errors = validate_form( )) {
        show_form($form_errors);
    } else {
        process_form( );
    } 
} else {
    show_form( );
}

function show_form($errors = '') {
    print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';

    if ($errors) {
        print '<ul><li>';
        print implode('</li><li>',$errors);
        print '</li></ul>';
    } 
    // Since we're not supplying any defaults of our own, it's OK
    // to pass $_POST as the defaults array to input_select and
    // input_text so that any user-entered values are preserved
    print 'Dish: ';
    input_select('dish', $_POST, $GLOBALS['main_dishes']);
    print '<br/>';

    print 'Quantity: ';
    input_text('quantity', $_POST);
    print '<br/>';

    input_submit('submit','Order');

    print '<input type="hidden" name="_submit_check" value="1"/>';
    print '</form>';
}

function validate_form( ) {
    $errors = array( );

    // The dish selected in the menu must be valid
    if (! array_key_exists($_POST['dish'], $GLOBALS['main_dishes'])) {
        $errors[  ] = 'Please select a valid dish.';
    }

    if ((! is_numeric($_POST['quantity'])) || (intval($_POST['quantity']) <= 0)) {
        $errors[  ] = 'Please enter a quantity.';
    }

    return $errors;
}

function process_form( ) {
    $_SESSION['order'][  ] = array('dish'     => $_POST['dish'],
                                 'quantity' => $_POST['quantity']);

    print 'Thank you for your order.';
} ?>

The form-handling code in Example 8-10 is mostly familiar. As in Examples Example 7-30 and Example 7-56, the form element printing helper functions are loaded from the formhelpers.php file. The show_form( ), validate_form( ), and process_form( ) functions display, validate, and process the form data.

Where Example 8-10 takes advantage of sessions, however, is in process_form( ). Each time the form is submitted with valid data, an element is added to the $_SESSION['order'] array. Session data isn't restricted to strings and numbers such as cookies. You can treat $_SESSION like any other array. The syntax $_SESSION['order'][ ] says "treat $_SESSION['order'] as an array and add a new element onto its end." In this case, what's being added on to the end of $_SESSION['order'] is a two-element array containing information about the dish and quantity that were submitted in the form.

The program in Example 8-11 prints a list of dishes that have been ordered by accessing the information that's been stored in the session by Example 8-10.

Example 8-11. Printing session data
<?php
session_start( );

$main_dishes = array('cuke' => 'Braised Sea Cucumber',
                     'stomach' => "Sauteed Pig's Stomach",
                     'tripe' => 'Sauteed Tripe with Wine Sauce',
                     'taro' => 'Stewed Pork with Taro',
                     'giblets' => 'Baked Giblets with Salt', 
                     'abalone' => 'Abalone with Marrow and Duck Feet');

if (count($_SESSION['order']) > 0) {
    print '<ul>';
    foreach ($_SESSION['order'] as $order) {
        $dish_name = $main_dishes[ $order['dish'] ];
        print "<li> $order[quantity] of $dish_name </li>";
    } 
    print "</ul>";
} else {
    print "You haven't ordered anything.";
}
?>

Example 8-11 has access to the data stored in the session by Example 8-10. It treats $_SESSION['order'] as an array: if there are elements in the array (because count( ) returns a positive number), then it iterates through the array with foreach( ) and prints out a list element for each dish that has been ordered.

    Previous Section  < Day Day Up >  Next Section