9

We have came across a strange issue while using PHP serialize/unserialize. We have serialized and stored in a particular string in mysql (UTF-8 collation). When unserializing the same it returns error.

Eg: String:

"Anoop did a great job cutting out pictures from the magazine that started with the letter P. "

Serialized data in DB :

s:96:"Anoop did a great job cutting out pictures from the magazine that started with the letter P. ";

While unserializing we got this error Notice - unserialize (): Error at offset 2 of 101 bytes. We noticed that the string length is different. What would be the cause for this issue.

Any help would be really appreciated. Thanks!

Manu Jose K
  • 238
  • 2
  • 9
  • 1
    http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset Look once,hope you find solution... – Akshay Paghdar Jan 28 '14 at 12:09
  • 2
    I stopped serialising data recently and started just storing json objects instead because the issues with serialise were driving me nuts. – Dave Jan 28 '14 at 12:17

3 Answers3

3

it is possible that you don't use utf-8 within your connection or your PHP context is not utf-8?

try to use the SQL:

SET CLIENT_ENCODING = utf8 

Befor you get your data.

try/verify:

ini_set ('default_charset' , 'UTF-8' );
setlocale (LC_ALL, 'de_DE.UTF-8'); # or what your favorit
Frank
  • 1,901
  • 20
  • 27
1

you see that there is a semicolon in the second string? UTF-8 does not use one byte all the time, it's 1 to 4 bytes.

When decoding strings from the database, make sure the input was encoded with the correct charset when it was input to the database.

I was using a form to create records in the DB which had a content field that was valid JSON, but it included curly apostrophes. If the page with the form did not have

in the head, then the data was sent to the database with the wrong encoding. Then, when json_decode tried to convert the string to an object, it failed every time.

Benjamin Eckstein
  • 884
  • 2
  • 9
  • 19
1

PHP serialize/unserialize has no problem ,

is do it like

$string = "Anoop did a great job cutting out pictures from the magazine that started with the letter P. ";
echo $string = serialize($string);
echo '<br>';
echo unserialize($string);

Then there is not error.

If you do direct unserialize the string then the same error display as you display previously.

$string = "Anoop did a great job cutting out pictures from the magazine that started with the letter P. ";
//echo $string = serialize($string);
echo '<br>';
echo unserialize($string);

It works for me you will try this.

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
Vishal Chanana
  • 114
  • 2
  • 6