PHP deserialization methods

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.