Reputation: 250
I've found a lot of information on session serialization from PHP 5.4 and below, but not much for PHP 7. A couple years ago I was advised to use $_SESSION['var'] = serialize($object);
when storing a class variable (class object { public $value; function __construct() { $this->value = new object2(); }}
).
Today, I transitioned my code from one development environment to another. The new one seems to dislike = serialize($object);
but appears to be fine with = $object
.
A few weeks ago I ran across a few posts that mentioned PHP always serializes variables before putting them into sessions, and since this event (During today's search), I've found many of those same posts.
In PHP's documentation, I ran across a mention of session_register()
, which apparently was supposed to be used to store objects in session variables... but it was apparently discontinued in 5.3.
Previous testing taught me that assigning session variables with class variables without serializing them first doesn't seem to keep track of class variables well, in particular situations like the above, where a variable is another class variable (object2).
The problems I had seemed hit-and-miss, and was in fact the reason I went looking for an answer and found serialize to begin with, and once I added serialize/unserialize (And no other changes), everything worked as intended.
So, here's my question: What's the 'real' way to handle object serialization for PHP sessions?
$_SESSION['var'] = serialize($object);
causes a 500 error. $_SESSION['var'] = $object
doesn't have an error, but due to previous issues, I'm not sure how well it works.
While on the topic, what's the best approach for unserializing? $object = unserialize($_SESSION['var']);
is my current approach. It doesn't result in an error, but for the sake of possible minor optimization and future knowledge, might as well cover the base.
If my approach (Using serialize()
and unserialize()
) is correct, what setting(s) would cause serialize()
to fail?
If there are any typos in any 'code' piece here, I wrote them inline in the post, so ignore them.
Upvotes: 2
Views: 1894
Reputation: 19555
You can save objects in sessions like any other value. At the end of the script the session got serialized and saved anyway:
When PHP shuts down, it will automatically take the contents of the
$_SESSION
superglobal, serialize it, and send it for storage using the session save handler.
The "main" problem is that for loading the session again the class definition for the object you try to load must be available/loaded before using the session_start();
call. Other than that everything should work just fine.
For your 500 server error, you have to check the error message and/or error log what the problem is.
Upvotes: 2