Jul 3
some element is a string with UTF8 data creates the serialized string
properly. However, unserialize function fails to unpack that data. I ran into this when setting session flashdata from my CodeIgniter application. The solution I find to work (not sure if it's perfect though) is to
use mb_unserialize function (found in comments of PHP manual). function mb_unserialize($serial_str)
{
$out = preg_replace('!s:(\d+):"(.*?)";!se',
"'s:'.strlen('$2').':\"$2\";'", $serial_str );
return @unserialize($out);
} To use this with CodeIgniter's session, just change Session's
_unserialize($data) function to use mb_unserialize instead of PHP's
original function. Grrr, I lost hours debugging this and finding a solution :(
PHP unserialize bug and CodeIgniter
Using PHP's serialize function to serialize and array or object wheresome element is a string with UTF8 data creates the serialized string
properly. However, unserialize function fails to unpack that data. I ran into this when setting session flashdata from my CodeIgniter application. The solution I find to work (not sure if it's perfect though) is to
use mb_unserialize function (found in comments of PHP manual). function mb_unserialize($serial_str)
{
$out = preg_replace('!s:(\d+):"(.*?)";!se',
"'s:'.strlen('$2').':\"$2\";'", $serial_str );
return @unserialize($out);
} To use this with CodeIgniter's session, just change Session's
_unserialize($data) function to use mb_unserialize instead of PHP's
original function. Grrr, I lost hours debugging this and finding a solution :(
Comments (1)
Jul 03, 2010
Milan Babuškov said...
Well, it turns out that the real problem was my MySQL tables not using UTF8 character set, so some characters were transcribed unproperly. Still a bug in PHP, it should really be more robust and work like "junk in - junk out" instead of current "junk in - nothing out" approach. This is why I'm using json_encode and json_decode for all my serializzation needs. It's much faster, less space consuming and less error prone.

