PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

An Introduction To PHP Sessions

How Do Sessions Work?

Sessions can be used in two ways. The first is cookie based, and the second is url based.

Most sessions are cookie based. What this means is that when a session is started, a cookie is set on the clients machine with a unique session ID or SID. The session variables are stored typically on a file on the server that matches the unique session ID. When a variable is required, the client or browser looks for the file matching the session ID and retrieves the corresponding variables from it. A typical session file stored in the default session file directory would look like this:

sess_fd51ab4d1820aa6ea27a01d439fe9959

Using our example session from above, this file would contain our session information in an array. An array of 1 is a little lacking for our purposes so let’s create several session variables. To demonstrate this let’s make a new page1.php with the following code…

Listing 5 page1.php
<?php
// begin the session
session_start();
 
// set the value of the session variable 'foo'
$_SESSION['foo']='bar';
 
// set the value of the session variable 'bar'
$_SESSION['bar']='foo';
 
// set the value of the session variable 'foobar'
$_SESSION['foobar']='fubar';
 
// echo a little message to say it is done
echo 'Setting session values';
?>

With this, the session variables foo, bar, and foobar have been stored in the $_SESSION array.

To access them we use the global variable $_SESSION and the array key of the variable we require. To view all the session variables, we can use the following code in our page2.php file.

Listing 6 page2.php
<?php
// begin the session
session_start();
 
// loop through the session array with foreach
foreach($_SESSION as $key=>$value)
    {
    // and print out the values
    echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
    }
?>

The output of page2.php should look like this:

Listing 7 Browser output from page2.php (listing-7.txt)
The value of $_SESSION['foo'] is 'bar'
The value of $_SESSION['bar'] is 'foo'
The value of $_SESSION['foobar'] is 'fubar'

As you can see above, when we loop throught the $_SESSION array, the value are displayed. The actual file that stores the session looks like this:

Listing 8 Session data as stored on the filesystem (listing-8.txt)
|s:3:"bar";bar|s:3:"foo";foobar|s:5:"fubar";

In This Article