PHP session_encode() and session_decode() with Examples

PHP normally handles session data encoding and decoding for us. We put values into $_SESSION, and PHP quietly takes care of storing and restoring them.

Most applications can happily ignore what happens underneath. But occasionally you need the encoded form of the current session, perhaps while working with custom session storage or debugging session data. That is where session_encode() and session_decode() come in.

These functions work directly with the current PHP session. They are not general-purpose replacements for serialize() and unserialize().

Quick answer

session_encode() converts the current $_SESSION data into PHP’s configured session-storage format and returns it as a string.

session_decode() does the reverse. It reads an encoded session string and loads the decoded values directly into $_SESSION.

  • session_encode() takes no arguments and returns a string or false.
  • session_decode($data) accepts an encoded session string and returns true or false.
  • An active session is required when using these functions.
  • The format depends on PHP’s session.serialize_handler setting.

How PHP session encoding works

Consider a session containing a username and a cart count:

<?php

session_start();

$_SESSION['username'] = 'David';
$_SESSION['cart_count'] = 3;

With PHP’s commonly used php session serialization handler, the encoded data can look similar to this:

username|s:5:"David";cart_count|i:3;

The string contains the session keys together with serialized representations of their values. The exact format is controlled by PHP’s session serialization handler, so application code should not depend on manually parsing this string.

Also, this is not necessarily the same format produced by calling serialize($_SESSION). Session serialization and PHP’s general-purpose serialize() function are related concepts, but they are separate mechanisms.

Using session_encode() in PHP

session_encode() encodes all values currently stored in $_SESSION. It does not accept individual variables or an array as an argument.

<?php

session_start();

$_SESSION['username'] = 'David';
$_SESSION['role'] = 'editor';
$_SESSION['cart_count'] = 3;

$encodedSession = session_encode();

if ($encodedSession === false) {
    echo 'Unable to encode the session.';
    return;
}

echo $encodedSession;

With the default php serialization handler, the output will look similar to this:

username|s:5:"David";role|s:6:"editor";cart_count|i:3;

The important point is that session_encode() encodes the entire active session. If you only want to serialize one value or a normal PHP array, use serialize() or another suitable data format instead.

Using session_decode() in PHP

session_decode() takes a session-encoded string and restores its values into the current $_SESSION array. It returns true on success and false on failure.

<?php

session_start();

$encodedSession = 'username|s:5:"David";role|s:6:"editor";cart_count|i:3;';

if (!session_decode($encodedSession)) {
    echo 'Unable to decode the session.';
    return;
}

echo $_SESSION['username'];
echo $_SESSION['role'];
echo $_SESSION['cart_count'];

The output is:

Davideditor3

Notice that session_decode() does not return the decoded values. The decoded values are written directly into $_SESSION.

This is a common source of confusion. The following code is therefore incorrect:

$decodedSession = session_decode($encodedSession);

// $decodedSession is a boolean, not the decoded session array.

If you need the restored values, read them from $_SESSION after session_decode() succeeds.

Encode and restore a session in one example

The following example shows both functions together. It encodes the current session, clears the session array, and then restores the values from the encoded string.

<?php

session_start();

$_SESSION['username'] = 'David';
$_SESSION['language'] = 'PHP';

$encodedSession = session_encode();

if ($encodedSession === false) {
    echo 'Unable to encode the session.';
    return;
}

$_SESSION = [];

echo 'Before decoding: ';
var_dump($_SESSION);

if (!session_decode($encodedSession)) {
    echo 'Unable to decode the session.';
    return;
}

echo 'After decoding: ';
var_dump($_SESSION);

After session_decode() runs successfully, $_SESSION contains the original values again:

array(2) {
  ["username"]=>
  string(5) "David"
  ["language"]=>
  string(3) "PHP"
}

This example is useful for understanding the behavior, but normal applications rarely need to manually encode and decode their own active session. PHP’s session subsystem already performs that work when it reads and writes session data.

session_encode() vs serialize()

It is easy to assume that session_encode() is just a session-specific spelling of serialize(). They are not interchangeable.

Function Purpose Input Result
session_encode() Encode the active PHP session Current $_SESSION Session-storage string
session_decode() Restore session-storage data Encoded session string Updates $_SESSION
serialize() Serialize a PHP value Any serializable PHP value Serialized string
unserialize() Restore a serialized PHP value Serialized string Decoded PHP value

Use session_encode() and session_decode() when you specifically need PHP’s session-storage representation. For ordinary arrays, objects, caching, or data transfer, these functions are usually the wrong tool.

When are session_encode() and session_decode() useful?

Most PHP applications never need to call these functions directly. PHP automatically reads session data at session_start() and writes it when the request ends.

Manual encoding and decoding become useful in less common cases, such as:

  • building or debugging a custom session storage mechanism,
  • inspecting the raw representation of the current session,
  • moving session data between compatible PHP session handlers,
  • testing how PHP stores session values.

If your goal is simply to save an array in a database or send structured data to another application, JSON handling in PHP or normal PHP serialization is usually a better fit.

The session.serialize_handler setting matters

PHP uses the session.serialize_handler configuration setting to decide how session data is encoded.

You can check the active handler with:

<?php

echo ini_get('session.serialize_handler');

A common value is:

php

Other handlers can produce a different encoded representation. Because of this, you should treat the string returned by session_encode() as an implementation format rather than something to manually split or edit.

For example, code that searches for the | separator and tries to parse the session string itself may appear to work with one handler and then fail when the configuration changes.

Common errors and fixes

Calling the functions before starting a session

These functions operate on the active session. Start the session first:

<?php

session_start();

$_SESSION['user_id'] = 42;

$encodedSession = session_encode();

Expecting session_decode() to return an array

session_decode() returns a boolean status. The decoded data goes into $_SESSION.

<?php

session_start();

if (session_decode($encodedSession)) {
    var_dump($_SESSION);
}

Trying to decode data from another format

session_decode() expects data created in the session format understood by the configured handler. A JSON string or the direct output of serialize() is not automatically valid session data.

Keep the encoder and decoder matched to the same purpose. Use json_encode() with json_decode(), serialize() with unserialize(), and PHP session encoding functions with PHP session data.

Security considerations

Session data often contains sensitive values such as user IDs, permissions, shopping-cart state, or workflow information. Treat an encoded session string as sensitive data too.

session_encode() does not encrypt the session. It only converts the current session into PHP’s configured storage format.

Avoid displaying encoded session data in production logs or error pages unless you are certain it contains nothing sensitive.

You should also avoid passing untrusted strings to session_decode(). The function changes the active $_SESSION data, so decoding arbitrary input can alter application state in unexpected ways.

Key points to remember

  • session_encode() converts the current $_SESSION contents into PHP’s session-storage format.
  • session_decode() restores an encoded session string directly into $_SESSION.
  • session_decode() returns true or false, not the decoded array.
  • The encoded format depends on session.serialize_handler.
  • These functions are mainly useful for session storage, debugging, and custom session handling.
  • For ordinary application data, use a format designed for that purpose instead of manually parsing PHP session strings.

Developer FAQ

Does session_encode() encode only one session variable?

No. session_encode() encodes the complete contents of the active $_SESSION array. It does not accept a variable or key as an argument.

Does session_decode() return the decoded session?

No. It returns true on success or false on failure. The decoded values are written directly into $_SESSION.

Can I use session_decode() with serialize() output?

Not as a general rule. session_decode() expects data in PHP’s configured session serialization format. Use unserialize() for data produced by serialize().

Do I need session_encode() to save normal PHP sessions?

No. PHP automatically serializes and stores session data when using its normal session handling. Call session_encode() only when you specifically need access to the encoded session representation.

Is session_encode() encrypted?

No. Encoding is not encryption. Do not expose the returned session string or assume that it protects sensitive session values.

Photo of Vincy, PHP developer
Written by Vincy Last updated: August 17, 2026
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Continue Learning

These related tutorials may help you continue learning.

4 Comments on "PHP session_encode() and session_decode() with Examples"

Leave a Reply

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

Explore topics
Need PHP help?