开发者

Unserialize sometimes returns false

I have this function in my application:

public function direct($theTree)
{
    $aTreeRoot = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $theTree);
    return unserialize($aTreeRoot);
}

It should never return false开发者_开发技巧 but in the error logs the error keep occuring which says it returned false.

However, I cannot replicate the error in my application. I'm trying to every possible way but it always works.

Is there something wrong with the function?

The $theTree comes from session.

Edit: The regex is there because: unserialize - Search for my regex there in the comments. It's supposed to solve a problem.


I have faced similar kind of issue earlier. I show u how i have solved it.

After you serialize data, apply base64_encode() e.g

$txt = base64_encode(serialize($txt));

And when you unserialize it

e.g.

 $txt = unserialize(base64_decode($txt));

Try this . Hope work for u as well. Good luck


I got some random behaviour on my code, but I think I found out why. I was using UTF-8 charset, and in my production server, it seems to produce these issues. Try this:

$txt = unserialize(utf8_encode($aTreeRoot));

Worked for me, hope it will for you too


I believe escaping the data you're serializing would also work as an alternative to base64.

$data = serialize($results);
$encoded = htmlentities($data);
echo '<input type="hidden" name="data" value="'.$encoded.'">';


I had similar problems. Turns out the column in the DB that was storing the serialized array had a collation of: latin1_swedish_ci

I changed the collation of the serialized data column to: utf8_bin and re-svaed the data and voila - problem solved.


For me the problem was that the string to unserialize needed to be trimmed! The error message was not helpful in this case and I stumbled upon the solution by looking at some other code.

$unserialized = unserialize(trim($serialized));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜