Reputation: 238
We 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 an error.
Eg:
Input 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?
Upvotes: 9
Views: 2771
Reputation: 124
PHP serialize/unserialize has no problem if you do it like this:
$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 are no errors.
If you do direct unserialize()
of the input string, then the same error shows up as you present in your question:
$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, please try this.
Upvotes: 2
Reputation: 2043
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
Upvotes: 2
Reputation: 894
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.
Upvotes: 1