views:

226

answers:

3

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?

+1  A: 

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.

nickf
+3  A: 

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.

troelskn
Really? I can't believe I didn't know this!
Wilco
Actually, after some research I'm not sure this is correct. Unless you use session_register() on a given instance, it will not be automatically serialized when saved to the session.I'll try to confirm with a test case to be 100% sure and post back what I find out.
Wilco
No, it is quite correct. And `session_register` is an old and deprecated way of using sessions - Stay clear of that.
troelskn
+1  A: 

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
}

http://www.php.net/manual/en/function.is-a.php

DreamWerx