This article mainly introduces PHP Serialization and deserialization methods. in some open source php source code, we often see some configuration files that store variable names and values similar to the format, for more information, see the following section. some configuration files store variable names and values similar to the format.
SerializationWhen you need these databases
DeserializationThe process is to restore the string to its original data structure. Let's talk about
How php serializes and deserializes data.
Php uses two functions to serialize and deserialize data,
SerializeAnd
Unserialize.
SerializeFormat the array into an ordered string
UnserializeReturns an array.
For example:
$ User = array ('Moe', 'Larry ', 'Curly'); $ user = serialize ($ stooges); echo''; print_r($user); echo '
'; print_r(unserialize($user));
Result:
a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}Array ( [0] => Moe [1] => Larry [2] => Curly )Note that when array values contain characters such as double quotes, single quotes, colons, or Chinese characters, they may be deserialized and garbled or the format may be disrupted.
You can useBase64_encodeAndBase64_decodeTwo functions.
For example:
$user=array('Moe','Larry','Curly'); $user=base64_encode(serialize($user)); $user=unserialize(base64_decode($user)); In this way, there will be no garbled issues,Base64 encoding increases the length of the stored string.
From the above, we can summarize one of our ownSerialization and deserialization functionsTo:
Function my_serialize ($ obj_array) {return base64_encode (gzcompress (serialize ($ obj_array);} // deserialize function my_unserialize ($ str) {return unserialize (gzuncompress (base64_decode ($ str )));}The above is to tell you how php serializes and deserializes data, and the cause and solution of garbled code or format disruption after deserialization, I hope this article will be helpful for your learning.