問題描述
$ser = 'a:2:{i:0;s:5:"héll?";i:1;s:5:"w?rld";}';//失敗$ser2 = 'a:2:{i:0;s:5:"hello";i:1;s:5:"world";}';//有效$out = 反序列化($ser);$out2 = 反序列化($ser2);打印_r($out);打印_r($out2);echo "
";
但是為什么?
我應該在序列化之前編碼嗎?怎么樣?
我使用 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?
和 w?rld
的長度是錯誤的,因為 PHP 本身不能正確處理多字節字符串:
echo strlen('héll?');//7echo strlen('世界');//6
但是,如果您嘗試 unserialize()
以下正確的字符串:
$ser = 'a:2:{i:0;s:7:"héll?";i:1;s:6:"w?rld";}';echo '';打印_r(反序列化($ser));echo '</pre>';
它有效:
數組([0] =>你好[1] =>世界)
如果您使用 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 反序列化因非編碼字符而失敗?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!