Recover Truncated PHP Serialized Arrays

PHP’s native serialization text format is the simplest way to store an arbitrary array in a database (or transmit it) without losing the types of its many values or their structure within the array. However, you might occasionally run into problems when the serialized string is longer than the database column that houses it. The resulting truncated string cannot be unserialized by PHP. The majority of the data might still be intact but PHP doesn’t know what to do with it; so I wrote a function, two actually, that does. (While PHP’s serialize() and unserialize() functions also work with objects this recovery function does not.)

Because the recursive function operates on and whittles down the actual serialized string while it attempts its recovery, a second function duplicates and prepares the string for repair leaving the original unchanged.

Example usage:

// the native unserialize() function returns false on failure
$data = @unserialize($serialized); // @ silences the default PHP failure notice
if ($data === false) // could not unserialize
    $data = repairSerializedArray($serialized); // salvage what we can

$data contains your original array (or what remains of it).

It goes without saying (in meatspace at least), if truncated serialized data is a frequent problem you probably need to reconsider your storage method (eg. increase the database column size or write the data to a file). But should the infrequent disaster strike this function will salvage what it can.

The repairSerializedArray() function has been downloaded 614 times.

False Positive
Shaun Inman
January 8th, 2008 at 12:08 pm