PHP save object in session

I am trying to save an object in $_SESSION , but the following:

 <?php $user = db->load( $username, $pass ) ; $_SESSION[ 'user' ] = $user ; # on subsequent page loads: $user = $_SESSION[ 'user' ] ; #retrieve the user from session 

Unfortunately this does not work.

The script tried to execute a method or access an object of an incomplete object. Make sure that the definition of the User class of the object you are trying to work with is loaded, _before_ unserialize () is called or provides the __autoload () function to load the class definition

If you are not using serialize ():

 <?php $user = db->load( $username, $pass ) ; $_SESSION[ 'user' ] = serialize( $user ) ; # on subsequent page loads: $user = unserialize( $_SESSION[ 'user' ] ) ; #retrieve the user from session 

I suppose it will need to be serialized because session information is stored on disk. But shouldn't PHP be smart enough to serialize stuff on its own?

And using serialize / _ unserialize_, will this work reliably now? Or do I need the __serialize() method in my PHP class?

+6
php serialization session
source share
5 answers

You will need __serialize() in your class if your object needs to take some action before serializing. For example, if it has a link to an open file, and this file must be properly closed before serialization.

+4
source share

Could you use var_export ? I just found out about it today, so maybe this is not very important.

+1
source share

As for the php compiler, all you do is write the object (serialized) to Array by another process that provides $ _SESSION on the next page. Serialization has nothing to do with writing to disk more than with memory, because the memory allocated for the various methods of your object will not be available on the next page. Serialization is how PHP rests on objects on different pages, and you have to do it yourself.

0
source share

Best use

 json_encode() json_decode() 
0
source share

Probably the best approach these days is to implement a Serializable interface with your class.

0
source share