Checking serial objects

Is there a built-in way to find out if a given session variable is a serialized object? Let's say I get 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 a way to check, or once serialized, PHP just sees the string as a string as a string?

+1


source to share


3 answers


It is a fairly common misconception that you must manually serialize objects before injecting them into a session. This is beside the point. You can simply assign an instance of an object to a slot in $_SESSION

, and PHP will automatically serialize and unserialize it for you between requests.



+3


source


A string is a string. I think the best you can do is just try to unserialize it, and if that works, it does. If it is not, it is not.



The only other option is to use a regex to see if it looks like a serialized object. Just getting started unserialize()

on this might be easier.

+1


source


You can use is_a ... Extract it from session and see if you just need to know the class name to check.

if (is_a($_SESSION['foo'], 'UserInfoObject')) {
  // We have one
}

      

It looks like PHP5 has an easier way:

if ($_SESSION['foo'] instanceof UserInfoObject) {
      // We have one
}

      

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

+1


source







All Articles