Arthur

Pemberton

Full-stack web applications developer


Solution to some PHP unserialize offset errors

September 17, 2018Arthur Pemberton0 Comments

I was getting PHP `unseralize` errors when working with some WordPress option values.

PHP Notice: unserialize(): Error at offset 4854 of 24578 bytes

One of the comments in the `unserialize` documentation was suggested matching all string values, and correct the string length. Working with that, and checking the area of breakage (byte 4854) I found a string which was declared as 64 characters, but serialized as 61. So I went ahead and adapted the 6 year snippet to work on PHP 7.1.

// $val = SERIALIZED_VALUE;

function fix_serialized_string_lengths($matches) {
	if ( strlen( $matches[2] ) == (int)$matches[1] ) return $matches[0];

	$idx = strpos( $matches[0], ':', 2 );

	return 's:' . strlen( $matches[2] ) . substr( $matches[0], $idx );
}

$arr = @unserialize( $val );

if ( $arr === FALSE ) {
	$val = preg_replace_callback(
		'!s:(\d+):"(.*?)";!s',
		'fix_serialized_string_lengths',
		$val
	);

	$arr = unserialize( $val );
}

Leave a Reply