unserialize(): Error at offset出现的原因分析以及解决方法

出现问题: 从数据库中取出数据后进行反序列化后,php报错  unserialize(): Error at offset xx of xx bytes;

分析原因:英文数据中含有中文字符串,所以我们就可以想到编码的问题,serialize()函数对在不同编码下对中文的处理结果是不一样的。

再讲gbk转换成utf8的格式后,每个中文的自己数从2个会增加到3个,所以会导致反序列化的时候判断字符长度出现问

解决方法 : 使用正则表达式将序列化的数组中的表示字符长度的值重新计算一遍

具体代码:php5.5以下 :

function mb_unserialize($str) {
    $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $str );
    return unserialize($out);
}

但是由于PHP本身 /e模式的漏洞,php5.5+,已经废弃了这种用法

PHP 5.5+

function mb_unserialize($str) {
    return preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$str);
}


猜你喜欢

转载自blog.csdn.net/json_ligege/article/details/79140348