PHP session_encode() function

Posted on Aug 07, 2022

Create a serialized session string using session_encode() in PHP

Photo from Unsplash

The PHP session_encode() function is used to serialize the available session data as an encoded string.

The function accepts no parameter, and it will return a string or false based on the available session data.

session_encode(): string|false

Hereโ€™s an example of calling the session_encode() function:

<?php
// ๐Ÿ‘‡ call session_start() to make $_SESSION available
session_start();

// ๐Ÿ‘‡ create some session data

$_SESSION['logged_in'] = true;
$_SESSION['username'] = 'Jack';

// ๐Ÿ‘‡ echo the call to session_encode()

echo session_encode();

// ๐Ÿ‘‡ returned value
// logged_in|b:1;username|s:4:"Jack";

The call to session_encode() in the code above returns:

logged_in|b:1;username|s:4:"Jack";

The function uses plain serialize function thatโ€™s diferent from the serialize() function.

If you use the serialize() function, the result would be:

a:2:{s:9:"logged_in";b:1;s:8:"username";s:4:"Jack";}

You need to call the session_start() function before calling the session_encode() function, or PHP will show the following notice:

Warning: session_encode(): Cannot encode non-existent session in ...

And thatโ€™s how the session_encode() function works in PHP ๐Ÿ‘

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.