Workaround for PHP unserialize return False
PHP provides serialize (serialization) and Unserialize (deserialization) methods.
Using serialize serialization, you can then use unserialize deserialization to get the original data.
<?php
$arr = Array (
' name ' => ' Fdipzone ', '
gender ' => ' Male '
);
$str = serialize ($arr); Serialization of
Echo ' serialize str: '. $str. ' \r\n\r\n ";
$content = Unserialize ($STR); Deserialize
the echo "Unserialize str:\r\n";
Var_dump ($content);
? >
Output:
Serialize str:a:2:{s:4: "Name"; S:8: "Fdipzone"; s:6: "Gender"; s:4: "Male";}
Unserialize str:
Array (2) {
[' name ']=>
string (8) ' Fdipzone '
[' Gender ']=>
string (4) "Male"
}
But the following example deserialization returns false
<?php
$str = ' a:9:{s:4: Time '; i:1405306402;s:4: "Name"; S:6: "New Morning"; s:5: "url"; s:1: "-"; s:4: "word"; s:1: "-"; S:5: " RPage "; s:29:" http://www.baidu.com/test.html "; s:5:" Cpage "; s:1:"-"; s:2:" IP "; s:15:" 117.151.180.150 "; s:7:" Ip_city " S:31: "Moving in Beijing, Beijing, China" s:4: "Miao"; s:1: "5";} ';
Var_dump (Unserialize ($STR)); BOOL (false)
?>
Check the serialized string and find the problem is in two places
S:5: "url"
s:29: "Http://www.baidu.com/test.html"
Both of these should be
S:3: "url"
S:30: "Http://www.baidu.com/test.html"
This problem occurs because the encoding of the serialized data is inconsistent with the encoding at the time of deserialization, for example, the database is latin1 and UTF-8 characters are not the same length.
In addition, there may be a single double quote, ASCII character "" "is resolved to" "," in C is a string of Terminator equals Chr (0), error resolution after 2 characters. \ r can also cause problems when calculating the length.
The workaround is as follows:
UTF8
function mb_unserialize ($serial _str) {
$serial _str= preg_replace ('!s: (\d+): "(. *?)";! Se ', ' ' s: '. strlen (' $ '). ': ' $2\ ";", $serial _str);
$serial _str= str_replace ("R", "", $serial _str);
Return Unserialize ($serial _str);
ASCII
function asc_unserialize ($serial _str) {
$serial _str = preg_replace ('!s: (\d+): "(. *?)";! Se ', ' "s:". strlen ("$"). ": \" $2\ ";", $serial _str);
$serial _str= str_replace ("R", "", $serial _str);
Return Unserialize ($serial _str);