Serialize function, possible problems

Serialize function, possible problems

The serialize() function returns a string representation of an array or object. Using serialize on an object will preserve the name of the class and all of its properties, however the methods are not saved.

To return the string representation back, use the unserialize() function. It is convenient to store the serialized string in a database or in a text file.

Problem

Sometimes, due to different encodings, the unserialize function throws an error like:

Notice: unserialize (): Error at offset 234 of 5455 bytes in ... at line ...

The way to eliminate it:

$text = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $text); 
$array = unserialize($text);
var_dump($array);
PHP

But this method does not always help, so the string should be additionally base64 encoded before saving.

$text = base64_encode(serialize($array));
...
$array = unserialize(base64_decode($text));
PHP
But a better method of storing arrays in a string is JSON, and it is also readable.
$text = json_encode($array, JSON_UNESCAPED_UNICODE);
...
$array = json_decode($json, true);
PHP
14.12.2016, updated 02.11.2021
46

Comments

to add a comment.

Other publications

Checking data with regular expressions
A collection of regular expressions with examples in PHP for validating data from form fields.
65
0
Automatic setting of the user's time zone
date_default_timezone_set sets the default timezone used by all date / time functions.
125
0
How to set up Last-Modified
The Last-Modified header helps to optimize the loading of web pages and make the job easier for search engines.
134
0
How to find out if a request came via AJAX
To distinguish between direct and AJAX requests, simply check the value of the $ _SERVER global variable
78
0
Session lifetime in PHP
By default, in php, the session lifetime is only 24 minutes, and cookies are saved until the browser is closed, such parameters are set on many hosting services.
362
0
Disable PHP caching
Sometimes on hostings PHP opcache caching is enabled by default. Edits were made in the code, but on the site everything is displayed as before...
67
0