Dax

Fix Corrupt Serialized Data

January 18th, 2008 · 5 Comments

I just had to deal with a shitload of serialized php data that had become corrupted with Windows carriage returns.

Errors like this were produced:

Notice: unserialize(): Error at offset 1060 of 41775.

If you’re getting that on a call to unserialize, it’s very likely that your string lengths do not match your serialized data. That looks something like this:

s:3:”fuck”;

In my example, fuck is four letters long, yet unserialize is told to read in 3 characters. That will produce an error that looks like this:

Error at offset 8 of 11 bytes

You can change that above 3 to a 4 pretty easily, but it’s much harder if your file is 300K long.

Here’s a function that will re-measure all your serialized strings and let you unserialize them. You’ll still have fucked up characters, but at least you’ll get your data back.


function fixFuckedData($data){

  $splits = preg_split("/s:([0-9]*):/”, $data);
  preg_match_all(”/s:([0-9]*):/”, $data, $lengths);
  $lengths = $lengths[1];

  for($i = 0; $i < sizeof($splits)-1; $i++){
    $text = $splits[$i+1];
    $pos = strpos($text, '";');
    $text = substr($text, 1, $pos-1);
    $text_len = strlen($text);
    if($lengths[$i] != $text_len)
      $lengths[$i] = $text_len;
      //echo "{$lengths[$i]} -> $text_len\n”;
  }
  //var_dump($lengths);
  //var_dump(unserialize($data));

  $return = $splits[0];
  for($i = 0; $i < sizeof($splits)-1; $i++){
    $return .= "s:{$lengths[$i]}:";
    $return .= $splits[$i+1];
  }
  return $return;
}

Tags: Work The Jerk

5 responses so far ↓

  • 1 SEO Bozo Box // Jan 22, 2008 at 12:57 pm

    You do understand that 99.9% of humans (including myself) do not know what the hell you are talking about here right?

    *goes off searching for serialized php data, carriage returns and corruption*

    =P

  • 2 Poppanator // Mar 20, 2008 at 11:48 am

    In most cases all you have to do is UTF8-encode the string and you’ll be fine. Maybe not in all cases but when I have stumbled upon this error it has solved it.

  • 3 firefox indir // Apr 3, 2008 at 3:29 am

    thank you !

  • 4 resimler // May 8, 2008 at 12:21 am

    Great help
    Thank you

  • 5 Justin // May 9, 2008 at 8:20 am

    Works great! Thanks so much!

Leave a Comment