问题
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