arbme
arbme

Reputation: 4931

Unserialize offset error, string length seems too long

I am trying to unserialize a longtext (utf8_unicode_ci) from a database query, but when I do I get the following error.

unserialize(): Error at offset 6 of 737 bytes

I guessed that my string was invalid so I outputted it to the browser. I noticed the string length was a little longer then what it was actually supposed to be. When I copy and paste the output in the browser and hard code it into the php the sting length changes to a smaller one and the unserialize works.

Database string...

ASCII - string(737) "a:10:{s:2:"id";i:2234950;s:13:"full_describe";s:11:"Brace start";s:6:"person";s:17:"Dr Aalok Y Shukla";s:8:"datetime";s:25:"2014-01-06T09:00:00+00:00";s:8:"duration";i:30;s:11:"on_waitlist";b:0;s:10:"company_id";s:5:"35927";s:8:"attended";b:1;s:6:"_links";a:2:{s:4:"self";a:1:{s:4:"href";s:60:"http://uk.bookingbug.com/api/v1/admin/35927/bookings/2234950";}s:6:"client";a:1:{s:4:"href";s:57:"http://uk.bookingbug.com/api/v1/admin/35927/client/809828";}}s:11:"appointment";a:1:{s:11:"description";s:11:"Brace start";}}"

Copied and pasted string into php...

ASCII - string(517) "a:10:{s:2:"id";i:2234950;s:13:"full_describe";s:11:"Brace start";s:6:"person";s:17:"Dr Aalok Y Shukla";s:8:"datetime";s:25:"2014-01-06T09:00:00+00:00";s:8:"duration";i:30;s:11:"on_waitlist";b:0;s:10:"company_id";s:5:"35927";s:8:"attended";b:1;s:6:"_links";a:2:{s:4:"self";a:1:{s:4:"href";s:60:"http://uk.bookingbug.com/api/v1/admin/35927/bookings/2234950";}s:6:"client";a:1:{s:4:"href";s:57:"http://uk.bookingbug.com/api/v1/admin/35927/client/809828";}}s:11:"appointment";a:1:{s:11:"description";s:11:"Brace start";}}" 

As you can see the strings are the same but the string from the database call shows the offset error.

Do I need to do some sort of decoding or formatting on the string returned from the database?

Thanks

Upvotes: 0

Views: 1017

Answers (1)

arbme
arbme

Reputation: 4931

The problem was that I was serializing multidimensional arrays which causes problems.

To fix just base64_encode() the string before you use serialize and vise versa when you use unserialize.

//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));

//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));

Article found at http://davidwalsh.name/php-serialize-unserialize-issues

Hope this helps others

Upvotes: 2

Related Questions