Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: serializing and unserializing string containing escaped characters

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?

like image 352
mikkelbreum Avatar asked Dec 12 '22 10:12

mikkelbreum


1 Answers

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)
like image 163
pb149 Avatar answered May 13 '23 21:05

pb149