Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP serialize/unserialize error

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!

like image 707
Manu Jose K Avatar asked Jan 28 '14 11:01

Manu Jose K


People also ask

What is unserialize function in PHP?

The unserialize() function converts serialized data back into actual data.

How can I serialize data in PHP?

unserialize() From the above code, we have a variable with serialized data, $string . We can unserialize the value of the variable using unserialize() function to get back to the original value of the complex array, $myvar. print_r( $newvar );

How do you unserialize data in MySQL?

The best approach is to have normalized table structure (different fields or tables). The next approach is to save data as a delimited string (e.g.: 0,US,1,19 ). Then you can use MySQL's SUBSTRING() or to use standard serialization mechanisms like JSON encode. thats right but the value is not inserted by external app.

How do I unserialize laravel data?

serialize is just a built-in, variable handling, PHP function. The counterpart of this is unserialize. You have to save the unserialized data in a variable -> $data=unserialize($serializedData) . After that you can access the data by using the index like $data["name"] for instance.


1 Answers

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
like image 64
Frank Avatar answered Nov 09 '22 23:11

Frank