PHP Session Encode Decode

Last modified on February 24th, 2017 by Vincy.

In PHP, session encodes and decode operations are automatically performed while storing session data into memory and reading stored session, respectively. While encoding, the $_SESSION array is converted into serialized string format and decoding reverts serialized string back to its original form. This serialization will not return the same format like PHP serialize().

encode_decode

The encoded session data contains all $_SESSION elements separated by the semicolon. Each element contains three parts: session index, session length, and session value. For example,

index1|s:length1:"value1";index2|s:length2:"value2";...

Session Encode Decode functions in PHP

PHP provides functions to perform session encode and decode manually. These functions are,

  • session_encode()
  • session_decode()

Before using these functions, we need to start the session using session_start(). Otherwise, we should set session.auto_start directive as 1 in PHP.ini file.

While invoking session_encode() it will take entire $_SESSION global array to serialize.

PHP session_decode() accepts serialized session data and converts it into an array. This function returns TRUE on successful decode. session_decode() reloads $_SESSION array with decoded data.

PHP Session Encode Decode Example

In this example, we have two session ids, product_code, and logged_in. While invoking session_encode(), it returns serialized string data into a variable.

When we decode serialized session data by using session_decode(), it reloads $_SESSION array with stored information.

In this example, we have changed the values of product_code and logged_in. But, the changed values are replaced by previously stored session data while invoking session_decode.

<?php
session_start();
$_SESSION["product_code"] = "2222";
$_SESSION["logged_in"] = "yes";
$enc_session = session_encode();
print "<b>Encoded Session Data:<br/></b>";
print $enc_session . "<br/><br/>";
// Changing session values
$_SESSION['product_code'] = "2000";
$_SESSION["logged_in"] = "no";
// printing $_SESSION
print "<b>SESSION Array:<br/></b>";
print "<pre>";
print_r($_SESSION);
print "</pre>";
session_decode($enc_session);
// printing Reloaded $_SESSION
print "<b>Reloaded SESSION Array:<br/></b>";
print "<pre>";
print_r($_SESSION);
print "</pre>";
?>

Output:

Encoded Session Data:
product_code|s:4:"2222";logged_in|s:3:"yes";
Changed SESSION values:
Array (
    [product_code] => 2000
    [logged_in] => no
)Reloaded SESSION Array:
Array(
    [product_code] => 2222
    [logged_in] => yes
)

Download PHP Session Encode Decode Source

This PHP code tutorial was published on November 22, 2013.

↑ Back to Top

Share this Article