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
14.12.2016, updated 14.05.2021
30

Comments

to add a comment.

Other publications

Regular Expression Shortcodes
Often on sites, it becomes necessary to insert dynamic information blocks into the texts of pages - banners, phones...
25
0
Checking data with regular expressions
A collection of regular expressions with examples in PHP for validating data from form fields.
48
0
Automatic setting of the user's time zone
date_default_timezone_set sets the default timezone used by all date / time functions.
111
0
Examples of using cURL in PHP
cURL PHP is a library for receiving and transmitting data via protocols such as HTTP, FTP, HTTPS. The library is used...
316
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.
97
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
60
0