How to store object in PHP session?

PHP session only allows serialized data. So we need to serialize object before storing it into PHP session and unserialize the serialized session data when retrieve and using it.

There are serialize() and unserialize() functions available and inbuild in PHP.

The following code shows how to store object in php session.

<?php 
session_start();
$object = new custom_session_object();
$_SESSION['custom_session'] = serialize($object);
?>

The following code shows how to retrieve object in php session.

<?php 
session_start();
$object = unserialize($_SESSION['custom_session']);
?>

Leave a Reply

Your email address will not be published.