Storing objects in PHP session

Solution 1:

You need to use the magic __sleep and __wakeup methods for PHP 5 Objects.

For example in the following code block:

$obj = new Object();

$_SESSION['obj'] = serialize($obj);

$obj = unserialize($_SESSION['obj']);

__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.

__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.

Solution 2:

Your code example isn't using references as the documentation was referring to. This is what php means by references:

$var =& $GLOBALS["var"];

As to putting objects into the session, PHP can store objects in $_SESSION. See http://example.preinheimer.com/sessobj.php.

What you are seeing is a bug in the order of calls to __sleep and __destruct (__destruct is being called before __sleep) and the session module fails to serialize the object at shutdown. This bug was opened on Sep 1, 2009.

Solution 3:

For safe serialization and unserialization encode and decode with base64_encode() and base64_decode() respectively. Below I pass a serialized Object to a session and unserialize it on the other page to regain the variable to an object state.

Page 1

<?php

require  $_SERVER['DOCUMENT_ROOT'] .'/classes/RegistrationClass.php';
$registrationData= new RegistrationClass();
$registrationData->setUserRegData();
$reg_serlizer = base64_encode(serialize($registrationData));   //serilize the object to create a string representation
$_SESSION['regSession'] = $reg_serlizer;
?>

Page 2

<?php
session_start();
require  $_SERVER['DOCUMENT_ROOT'] .'/classes/RegistrationClass.php';
$reg_unserilizeObj = 
unserialize((base64_decode($_SESSION['regSession'])));
$reg_unserilizeObj->firstName;
?>

This article describes issues that may be faced by not doing so. issuses with php serialization/unserialization

Solution 4:

You were right saying you can not store references in sessions variables assigning an object in PHP 5 and above is doing just that assigning the reference not the obj

That its why you would need to serialize the object (implementing also __sleep in the Class) and assigning the string to a session variable

and deserializing it later (implementing also __wake in the Class) from the session variable later on.