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

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办