PHP Tutorial :: Sessions (I)

PHP Example #78

Setting a session

Sessions use a cookie called PHPSESSID that stores a random alphanumeric value. Whenever a session is started in a page, the PHP interpreter checks wether this cookie exists or not. Each client browser receives a different session ID, that uniquely identifies it in the server. This allows the server to keep separate stocks of data for every client. To start a session in a page, we use the function session_start() at the beginning of the page, samely as we do with setcookie(). By setting On the configuration directive session.auto_start we can start automatically sessions in all our pages, so we don't have to call session_start() in every page.

Data of a session is stored in the auto-global array $_SESSION[], and by manipulating this array, we can control the session. This example uses a counter to track how many times the user has visited the page. Reload this page and you will see how each reload is tracked and stored in $_SESSION[]. The first time that the user enters the page, the session is created but the array remains empty. In subsequents requests (page loads) the function session_start() will retrieve the session from the server and the data will be available for the client.

// The session is declared in the very beginning of the page
<?php session_start(); ?>

$_SESSION['count'] = $_SESSION['count'] + 1;
print 'You have looked at this page ' . $_SESSION['count'] . ' times.';
You have looked at this page 1 times.

PHP Example #79

Setting a session

This example shows a form where an user can select a dish and a quantity; the information is stored in the session variable named "order". Unlike cookies, sessions can store arrays and hence $_SESSION[] works just like any array.

// The session is declared in the very beginning of the page
<?php session_start(); ?>

require 'scripts/formhelpers.php';
$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()) {
} else {
} else {
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 aren't providing any default value, it is appropriate to pass
// $_POST as the default array for input_select and input_text to prevent
// any data facilitated by the user to be 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.';

PHP Example #80

Retrieving a session

This example shows the choice made in the previous example by retrieving it from $_SESSION['order'].

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

PHP Example #81

Configuring sessions

By default a session is kept active while it is requested at least every 24 minutes. The configuration directive session.gc_maxlifetime sets the idle time allowed between requests to keep the session active; by default the value is set to 1440 seconds (24 minutes). To alter this value, it can be used as well the function ini_set(), which must be invoked before session_start().

Sessions that have expired are not instantly deleted, however; by default, anytime that a session request is made in the server, there is a 1% probability that the expired sessions are deleted. The configuration directive session.gc_probability sets the percentage of probabilities used in the server to start an expired session cleaning. The example that can be seen below sets the duration of sessions in the server to 10 minutes and requires that for every request made the cleaning of expired sessions be executed.

If sessions are activated with the configuration directive session.auto_start, the values of session.gc_maxlifetime and session.gc_probability no longer can be set with ini_set(), but only by means of the server configuration.

// Sets the expiration time of the session in 600 seconds
ini_set('session.gc_maxlifetime', 600);
// Sets the probability of cleaning expired sessions to 100%
ini_set('session.gc_probability', 100);
// Starts the session