Remembering Users: Storing and Retrieving Information in PHP

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

Example 10-10. Counting page accesses with a session

session_start();

if (isset($_SESSION[‘count’])) {

$_SESSION[‘count’] = $_SESSION[‘count’] + 1;

} else {

$_SESSION[‘count’ ] = 1 ;

}

print “You’ve looked at this page “ . $_SESSION[‘count’] . ‘ times.’;

The first time a user accesses the page in Example 10-10, 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, the code checks for a count key in the $_SESSION array. If it’s there, then the value is incremen­ted. If not, it’s set to 1 to mark the first visit. 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 engine keeps track of the contents of $_SESSION separately for each session ID. When your program is running, $_SESSION contains the saved data for one ses­sion 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 10-11 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 10-11. Saving form data in a session

require ‘FormHelper.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 ($_SERVER[‘REQUEST_METHOD’] == ‘POST’)

{

list($errors, $input) = validate_form();

if ($errors)

{

show_form($errors);

} else {

process_form($input);

}

} else {

show_form();

}

function show_form($errors = array()) {

// No defaults of our own, so nothing to pass to the

// FormHelper constructor

$form = new FormHelper();

// Build up the error HTML to use later

if ($errors) {

$errorHtml = ‘<ul><li>’;

$errorHtml .= implode(‘</li><li>’,$errors);

$errorHtml .= ‘</li></ul>’;

} else {

$errorHtml = ;

}

// This form is small, so we’ll just print out its components

// here

print <<<_FORM_

<form method=”POST” action=”{$form->encode($_SERVER[‘PHP_SELF’])}”>

$errorHtml

Dish: {$form->select($GLOBALS[‘main_dishes’],[‘name’ => ‘dish’])} <br/>

Quantity: {$form->input(‘text’,[‘name’ => ‘quantity’])} <br/>

{$form->input(‘submit’,[‘value’ => ‘Order’])}

</form>

_FORM_;

}

function validate_form()

{

$input = array();

$errors = array();

// The dish selected in the menu must be valid

$input[‘dish’] = $_POST[‘dish’] ?? ”;

if (! array_key_exists($input[‘dish’], $GLOBALS[‘main_dishes’])) {

$errors[] = ‘Please select a valid dish.’;

}

$input[‘quantity’] = filter_input(INPUT_POST, ‘quantity’, FILTER_VALIDATE_INT,

array(‘options’ => array(‘min_range’ =>   )));

if (($input[‘quantity’] === false) || ($input[‘quantity’] === null)) {

$errors[] = ‘Please enter a quantity.’;

}

return array($errors, $input);

}

function process_form($input) {

$_SESSION[‘order’][] = array(‘dish’    => $input[‘dish’],

‘quantity’ => $input[‘quantity’]);

print ‘Thank you for your order.’;

}

The form-handling code in Example 10-11 is mostly familiar. As in Examples 8-28 and 8-53, the form-element-printing helper class is loaded from the FormHelper.php file. The show_form(), validate_fom(), and process_form() functions display, validate, and process the form data.

Where Example 10-11 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, like 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 to the end of $_SES SION[‘order’] is a two-element array containing information about the dish and quantity that were submitted in the form.

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

Example 10-12. Printing session data

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 (isset($_SESSION[‘order’]) && (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 10-12 has access to the data stored in the session by Example 10-11. 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.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *