PHP: serializing and unserializing string containing escaped characters

…衆ロ難τιáo~ 提交于 2019-12-05 16:23:38

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.

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)

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\'" 
barkgj

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

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