PHP: serializing and unserializing string containing escaped characters

醉酒当歌 提交于 2019-12-07 09:26:36

问题


How do I correctly serialize and unserialize a string containing escaped characters?

Given:

$data = "\'test\'";
$out= serialize($data);
print_r($out); // ->  s:8:"\'test\'";

The problem here is, that the string length is not accepted by unserialize:

$out = 's:8:"\'test\'"';
var_dump(unserialize($out)); // -> bool(false)

But if I change the string length to 6 (ignoring the escape chars):

$out = 's:6:"\'test\'"';
var_dump(unserialize($out)); // -> string(6) "'test'"

It unserializes correctly.

What would be a good way of handling this problem?


回答1:


Your test cases don't match, you're wrapping the string in double quotes in your first example and single quotes in the second, causing the escape character to be taken literally in the latter.

$out = '\'test\'';

is different from

$data = "\'test\'";

if you do

$data = "\'test\'";
$out= serialize($data);
print_r($out); // ->  s:8:"\'test\'";
$data = unserialize($out);
print_r($data); // -> \'test\'

it will work.




回答2:


I would try calling base64_encode() before you serialize the data and then base64_decode() after unserializing the data.

$data = "\'test\'";
$out= serialize(base64_encode($data));
var_dump(base64_decode(unserialize($out))); // -> bool(false)



回答3:


The problem is, that your escape characters are being evaluated by PHP. If you want to keep them intact, you should escape them too :) Example:

$out = 's:8:"\'test\'"'; // $out = s:8:"'test'"
$out = 's:8:"\\\'test\\\'"'; // $out = s:8:"\'test\'"

var_dump(unserialize($out)); // string(8) "\'test\'" 



回答4:


Instead of using serialize and deserialize, try json_encode and json_decode. The latter will do the (un)escaping of the quotes for you.



来源:https://stackoverflow.com/questions/7146570/php-serializing-and-unserializing-string-containing-escaped-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!