PHP session_encode() function

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 ๐Ÿ‘

More PHP tutorials

See all