Is there a built-in way to know if a given session variable is a serialized object? Say I retrieve a value like $_SESSION['foo'], but I don't know if it was originally a string or if it is a serialized object. Is there some way to check, or once serialized does PHP just see a string as a string as a string?
It's a pretty common misconception that you have to manually serialize objects before putting them in session. That is not the case. You can simply assign an object instance to a slot in $_SESSION
, and PHP will automagically serialize and unserialize it for you, between requests.
A string is a string is a string. I think the best you'll be able to do is just try to unserialize it, and if it works, it works. If it doesn't, it doesn't.
The only other option would be to use a regex to see if it "looks" like a serialized object. Just running unserialize()
on it might be easier though.
You could use is_a ... Pull it out of the session and see, you just need to know the classname to check for.
if (is_a($_SESSION['foo'], 'UserInfoObject')) {
// We have one
}
It looks like PHP5 has an easier method:
if ($_SESSION['foo'] instanceof UserInfoObject) {
// We have one
}