Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex/ code to fix corrupt serialized PHP data.

Tags:

I have a massive multidimensional array that has been serialised by PHP. It has been stored in MySQL and the data field wasn't large enough... the end has been cut off... I need to extract the data... unserialize wont work... does anyone know of a code that can close all the arrays... recalculate string lengths... it's too much data to do by hand.

Many thanks.

like image 400
Simon Avatar asked Jun 30 '10 11:06

Simon


2 Answers

This is recalculating the length of the elements in a serialized array:

$fixed = preg_replace_callback(     '/s:([0-9]+):\"(.*?)\";/',     function ($matches) { return "s:".strlen($matches[2]).':"'.$matches[2].'";';     },     $serialized ); 

However, it doesn't work if your strings contain ";. In that case it's not possible to fix the serialized array string automatically -- manual editing will be needed.

like image 190
Emil M Avatar answered Sep 28 '22 03:09

Emil M


Solution:

1) try online:

Serialized String Fixer (online tool)

2) Use function:

unserialize( serialize_corrector($serialized_string ) ) ;

code:

function serialize_corrector($serialized_string){     // at first, check if "fixing" is really needed at all. After that, security checkup.     if ( @unserialize($serialized_string) !== true &&  preg_match('/^[aOs]:/', $serialized_string) ) {         $serialized_string = preg_replace_callback( '/s\:(\d+)\:\"(.*?)\";/s',    function($matches){return 's:'.strlen($matches[2]).':"'.$matches[2].'";'; },   $serialized_string );     }     return $serialized_string; }  

there is also this script, which i haven't tested.

like image 22
T.Todua Avatar answered Sep 28 '22 01:09

T.Todua