Check to see if a string is serialized?

前端 未结 11 1675
情歌与酒
情歌与酒 2020-11-29 17:16

What\'s the best way to determine whether or not a string is the result of the serialize() function?

https://www.php.net/manual/en/function.serialize

11条回答
  •  醉话见心
    2020-11-29 18:06

    I'd say, try to unserialize it ;-)

    Quoting the manual :

    In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued.

    So, you have to check if the return value is false or not (with === or !==, to be sure not to have any problem with 0 or null or anything that equals to false, I'd say).

    Just beware the notice : you might want/need to use the @ operator.

    For instance :

    $str = 'hjkl';
    $data = @unserialize($str);
    if ($data !== false) {
        echo "ok";
    } else {
        echo "not ok";
    }
    

    Will get you :

    not ok
    


    EDIT : Oh, and like @Peter said (thanks to him!), you might run into trouble if you are trying to unserialize the representation of a boolean false :-(

    So, checking that your serialized string is not equal to "b:0;" might be helpful too ; something like this should do the trick, I suppose :

    $data = @unserialize($str);
    if ($str === 'b:0;' || $data !== false) {
        echo "ok";
    } else {
        echo "not ok";
    }
    

    testing that special case before trying to unserialize would be an optimization -- but probably not that usefull, if you don't often have a false serialized value.

提交回复
热议问题