Tag Archives: Unserialize() error

Unserialize(): cause analysis and solution of error at offset

Unserialize (): Cause analysis and solution of Error at Offset2016-09-10
Classification: Practical knowledge
Reading (5590).
Comments (0)

In the use of PHP’s unserialize function, the following error occurs when a string or data is fetched from a database in Chinese

Notice: unserialize(): Error at offset xx of xxx bytes in C:\toolmao\php\index.php on line 21

Speaking of Chinese, we must first think of coding, so let’s see how the serialize function handles Chinese with different file codes, using the same piece of code and testing the file with different codes

echo serialize(array('name'=>'Tools','url'=>'http://www.toolmao.com/'));

Looking at the UTF8 effect first, we find that the Length of the Chinese “tool cat” is 9

When the file code is GB2312, the length of Chinese “tool cat” is 6

Therefore, when we take out the database encoding GBK and other Chinese encoding, and then use transcoding function to convert to UTF8, and then use unserialize function, this problem will occur because the length of Chinese in different encodings is different. One might say that SET NAMES is not acceptable when the database is pulled out, but some databases (such as Access and SQLite) do not support this. So when the code does not match, you must take out the data transcoding. So how do you do that?Here’s the solution:
Above, we have already known the cause of Error at offset in unserialize. Therefore, it is easy to solve this problem. Just replace the Error length with the regular function.

unserialize(preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $string))
From:http://www.phpddt.com/php/unserialize-error-at-offset.html

However, due to the PHP problem, the/E mode has been compromised, so this usage has been removed since PHP5.5, so don’t worry if you are using PHP5.5 +, here is another solution

preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$data);

The above is my actual development encountered in the problem, combined with the solution of the net and their own actual situation finally write the code, I hope to help you!