Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Object in PHP Session

In PHP, is it considered best practice to store the complete object as a session variable?

From my experience, sometimes it works and sometime not. Is there any specific reason for it?

Example:

session_start();
$object = new sample_object();
$_SESSION['sample'] = $object;
like image 768
David Somekh Avatar asked May 13 '26 20:05

David Somekh


1 Answers

Use serialize() in PHP before store your object, and call unserialize() when retrieve your object from session.

store object

session_start();
$object = new sample_object();
$_SESSION['sample'] = serialize($object);

retrieve object

session_start();
$object = unserialize($_SESSION['sample']);
like image 66
Dolly Aswin Avatar answered May 15 '26 09:05

Dolly Aswin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!