ylliX - Online Advertising Network

How to fix broken serialized string in php?

From time to time previously serialized array will get broken. The most common problem occurs when string length is invalid so instead of

a:2:{i:758;s:4:"test";i:759;s:4:"test";}

you have

a:2:{i:758;s:4:"test";i:759;s:9:"test";}

becouse someone edited something directly in db, in this case to make php unserialize() function to work again, just do this magic:

[php]
$data = html_entity_decode($data, ENT_QUOTES, ‘UTF-8’);
$data = preg_replace(‘!s:(\d+):"(.*?)";!e’, "’s:’.strlen(‘$2′).’:\"$2\";’", $data );
$data = unserialize($data);
[/php]

and you will get all strings lenths to be fixed again.

2 thoughts on “How to fix broken serialized string in php?

  1. A more secure solution would be to use preg_replace_callback:

    $data = preg_replace_callback(
      '/s:(\d+):"(.*?)";/',
      function ($m){
        $len = strlen($m[2]);
        $data = $m[2];
        return "s:$len:\"$data\";";
      }, 
      $data );
    

Leave a Reply to Benjamin MurauerCancel reply