dongyi6845
2014-11-25 18:53
浏览 23
已采纳

php反序列化存储在DB字段中的序列化对象

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问答提供 功能建议

我正在尝试序列化一个php对象,然后对其进行反序列化。

我序列化,然后将获取的字符串放在一个文件中,然后读取文件并反序列化,一切正常。

当我序列化,然后将获得的字符串存储在数据库字段中时, 然后读回来并尝试反序列化,这不起作用。 我注意到我从数据库中读取的字符串包含一些特殊字符(如& 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:

    <?php
    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:

    O:3:"Foo":1:{s:8:"Foobar";s:3:"baz";}
    

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

    O(4f):(3a)3(33):(3a)"(22)F(46)o(6f)o(6f)"(22):(3a)1(31):(3a){..
        (7b)s(73):(3a)8(38):(3a)"(22)(0)F(46)o(6f)o(6f)(0)b(62)a(61)r(72)"
                                      ^ ----------------^-- there's two of your NULL bytes.
    
    点赞 评论

相关推荐 更多相似问题