2014-11-25 18:53
浏览 23


I am trying to serialize a php object then unserialize it.

When I serialize, and then put the obtained string in a file, then read the file and unserialize, all works fine.

When I serialize, and then store the obtained string in a database field, then read it back and try to unserialize, that does not work. I noticed that the string I read from the database contains some special characters (like &quote;). I tried to get rid of those by using htmlspecialchars_decode, but still the unserialize does not work (the message : unserialize(): Error at offset 1774 of 24239 bytes). When I try to see those characters I do not see anything special.

Any help?

图片转代码服务由CSDN问答提供 功能建议



当我序列化,然后将获得的字符串存储在数据库字段中时, 然后读回来并尝试反序列化,这不起作用。 我注意到我从数据库中读取的字符串包含一些特殊字符(如& quote;)。 我试图通过使用htmlspecialchars_decode来摆脱它们,但仍然unserialize不起作用(消息:unserialize():错误在偏移1774 24239字节)。 当我试图看到那些字符时,我没有看到任何特别的东西。


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dougua3706 2014-11-25 19:09

    Store it in a BLOB / BINARY column, not in TEXT or (VAR)CHAR. Serialization of certain properties contain NULL-bytes for instance.

    As @Barmar says, the documentation states this explicitly:

    Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

    To illustrate:

    class Foo { private $bar = "baz";} 
    $string = serialize(new Foo()); 
    echo $string.PHP_EOL;
    for($i = 0; $i < strlen($string); $i++){ 
        echo $string[$i]."(".dechex(ord($string[$i])).")";

    Outputs visually:


    BUT: there's more then the eye can see:

                                      ^ ----------------^-- there's two of your NULL bytes.
    点赞 评论

相关推荐 更多相似问题