PHP function: is_serialized()

I needed a way to detect if some values were serialized or not, annoyingly PHP does not provide a method for this. I’d also rather not perform unserialize() on everything to check for a serialized string in the name of efficiency, so instead I came up with a simple function to detect serialized data. The result of my endeavours is a function that checks a string for basic makers of the PHP serialization form, it only checks the variables type and not any deeper values inside arrays or objects, if this preliminary testing is successful then unserialize() is invoked to provide the final proof. The unserialized form is available as an option argument passed by reference and the return value is a boolean, true for boolean or false otherwise. You can find the function on Gist or below.

About Chris

Twenty-something year old computer science graduate living in the West Midlands, working as a PHP software developer for a local company.
This entry was posted in Code Snippets, Web and tagged , , . Bookmark the permalink.

6 Responses to PHP function: is_serialized()

  1. Alexandre says:

    thank you!

    Funcionou muito bem pra mim, obrigado!

  2. rand says:

    Great function and it saves me a lot of time. I think similar function should be included in PHP core. Thanks for sharing!

  3. bunyamin says:

    I appreciate you share the function, it is really useful

  4. bunyamin says:

    I have just come up with an another solution which seems better, here is the link: http://stackoverflow.com/questions/1369936/php-check-to-see-if-a-string-is-serialized

  5. Lars says:

    function is_serialized($str){
    $st["array"]=”a}”;$st["object"]=”O}”;$st["string"]=”s;”;$st["integer"]=”i;”;
    $st["float"]=”d;”;$st["bool"]=”b;”;
    foreach($st as $t => $p){if(preg_match(“/^”.$p[0].”:.*\\”.$p[1].”$/is”,$str))return $t;}
    return false;
    }

    check for NULL makes no sense as if you expect a null, the string is whether null, “” or deserializable.

  6. Tbag says:

    This is ok too.

    function is_serialized($val){
    if (!is_string($val)){ return false; }
    if (trim($val) == "") { return false; }
    if (preg_match("/^(i|s|a|o|d):(.*);/si",$val)) { return true; }
    return false;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>