PHP Error: unserialize() [function.unserialize]: Error at offset 118 of 512

Lately I got this error in my script while trying to decode serialized UTF-8 string:

unserialize() [function.unserialize]: Error at offset 118 of 512

Here’s a simple solution I found. Instead of using unserialize() you should use mb_unserialize():

function mb_unserialize($str)
{
    $res = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $str );
    return unserialize($res);
}

You can also think about replacing in your program serialize() + unserialize() with json_encode() + json_decode(). Your data should be safer then.

This entry was posted on Monday, May 30th, 2011 at 1:03 pm and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “PHP Error: unserialize() [function.unserialize]: Error at offset 118 of 512”

  1. Ray Says:

    Your can use base64 or url to encode/encode your content before serialize()

  2. Marc Geldon Says:

    Hey! ;-) Thanks a lot. That solved my “offset” problem… ;-)

  3. admin Says:

    Yes, but base64 makes the data longer (takes more space) than json_encode.

Leave a Reply

 
TopOfBlogs Web Development & Design Blogs