[ Team LiB ] Previous Section Next Section

Encoding and Decoding Session Variables

You have already seen the way in which PHP encodes and saves (serializes) session variables when you peeked into a session file. You can, in fact, gain access to the encoded string at any time with session_encode(). This can be useful in debugging your session-enabled environments. You can use session_encode() to reveal the state of all session variables:

print session_encode()."<br/>";
// sample output: products|a:2:{i:0;s:8:"Hal 2000";i:1;s:6:"Tardis";}

From the sample output in the previous fragment, you can see the session variables that are stored. You can use this information to check that variables are being registered and updated as you expect. session_encode() is also useful if you need to freeze-dry session variables for storage in a database or file.

After having extracted an encoded string, you can decode it and resurrect its values using session_decode(). The following code fragment demonstrates this process:

$_SESSION = array(); // there should now be no session variables
session_decode( "products|a:2:{i:0;s:8:\"Hal 2000\";i:1;s:6:\"Tardis\";}" );
foreach ( $_SESSION['products'] as $p ) {
  print "$p<br/>\n";
// Output:
// Hal 2000
// Tardis

We start a session as usual. To ensure that we are working with a blank canvas, we clear all session elements by assigning an empty array to $_SESSION. We then pass an encoded string to session_decode(). Rather than returning values, session_decode() populates the $_SESSION array with the unserialized variables. We confirm this by looping through the newly resurrected $_SESSION['products'] array.

    [ Team LiB ] Previous Section Next Section