PHP unserialize失败与非编码字符? [英] PHP unserialize fails with non-encoded characters?

查看:419
本文介绍了PHP unserialize失败与非编码字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ ser ='a:2:{i:0; s:5:héllö; i:1; s:5:wörld;}'; // failed 
$ ser2 ='a:2:{i:0; s:5:hello; i:1; s:5:world // works
$ out = unsserialize($ ser);
$ out2 = unserialize($ ser2);
print_r($ out);
print_r($ out2);
echo< hr>;

但是为什么?

我应该在序列化之前编码吗?如何?



我使用Javascript将序列化字符串写入隐藏字段,而不是PHP的$ _POST

在JS中,我有类似:

  function writeImgData(){
var caption_arr = new Array();
$('。album img')。each(function(index){
caption_arr.push($(this).attr('alt'));
});
$(#hidden-field)。attr(value,serializeArray(caption_arr));
};

解决方案

unserialize )失败:

  $ ser ='a:2:{i:0; s: 5:héllö; i:1; s:5:wörld;}'; 

因为héllö code>wörld是错误的,因为PHP本身不能正确处理多字节字符串:

  echo strlen('héllö'); // 7 
echo strlen('wörld'); // 6

但是如果您尝试 unserialize()以下正确的字符串:

  $ ser ='a:2:{i:0; s:7: héllö; i:1; s:6:wörld;}'; 

echo'< pre>';
print_r(unserialize($ ser));
echo'< / pre>';

工作原理:

  Array 

[0] =>héllö
[1] =>wörld

如果使用PHP serialize(),它应该正确计算多字节字符串索引的长度



另一方面,如果你想使用多种(编程)语言的序列化数据,你应该忘记它,并移动到像JSON,这是更多标准化。


$ser = 'a:2:{i:0;s:5:"héllö";i:1;s:5:"wörld";}'; // fails
$ser2 = 'a:2:{i:0;s:5:"hello";i:1;s:5:"world";}'; // works
$out = unserialize($ser);
$out2 = unserialize($ser2);
print_r($out);
print_r($out2);
echo "<hr>";

But why?
Should I encode before serialzing than? How?

I am using Javascript to write the serialized string to a hidden field, than PHP's $_POST
In JS I have something like:

function writeImgData() {
    var caption_arr = new Array();
    $('.album img').each(function(index) {
         caption_arr.push($(this).attr('alt'));
    });
    $("#hidden-field").attr("value", serializeArray(caption_arr));
};

解决方案

The reason why unserialize() fails with:

$ser = 'a:2:{i:0;s:5:"héllö";i:1;s:5:"wörld";}';

Is because the length for héllö and wörld are wrong, since PHP doesn't correctly handle multi-byte strings natively:

echo strlen('héllö'); // 7
echo strlen('wörld'); // 6

However if you try to unserialize() the following correct string:

$ser = 'a:2:{i:0;s:7:"héllö";i:1;s:6:"wörld";}';

echo '<pre>';
print_r(unserialize($ser));
echo '</pre>';

It works:

Array
(
    [0] => héllö
    [1] => wörld
)

If you use PHP serialize() it should correctly compute the lengths of multi-byte string indexes.

On the other hand, if you want to work with serialized data in multiple (programming) languages you should forget it and move to something like JSON, which is way more standardized.

这篇关于PHP unserialize失败与非编码字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆