WordPress-Christmas-2010-14

unserialize() Error at Offset… Different solutions

The problem is not always obvious, for example the error message in relation to the function unserialize(). If you look around the net to help you find countless search and few answers, because usually the problem lies in the source, in the passed value. But not always you can control it, especially in debugging helpers there are different contents.

To help some people who are seeking help, here are some solutions you can work with. Some are to be used only in conjunction with WordPress, because the function comes from the core. But there are similar things, of course, even without WP.

The first solution can be found directly in the comments for the function of PHP.net.

$object = preg_replace( '!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $object );

Similar this approach:

$object = preg_replace( '/;n;/', ';N;', $object );

Alternative others prefer to use trim()

$object = trim( $object );

But even with these solutions you can't always get what you want, you need a queries which gives you the answer whether it is serialized data or not. Usually unserialize() takes care of it, but as I said, this does not always help. WordPress provides its own functions for this.

  • is_serialized( $data )
  • is_serialized_string( $data )

With these two functions it can be queried in a clean way.
But also there you can use a simple snippet. Not the best practice maybe, therefore, I prefer to use the functions or outside of WP, a separate function, see Gist 1415653.

$is_serialized = preg_match( "/^(O:|a:)/", $object );

It may help one or the other, otherwise I use it as a memory aid.

Comments are closed.

2 comments

  1. Pau Iglesias

    Hi, I developed a PHP script that fix this issues working over database dumps, very useful if you are migrating websites to another servers and need to change values like paths, domains, or other serialized data used by WordPress:

    https://github.com/Blogestudio/Fix-Serialization

    Regards,
    Pau

One pingback

  1. Adventskalender vom 14. Dezember « F-LOG-GE