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?

  • 写回答

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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行