Php Serialization and deserialization

Source: Internet
Author: User
This article explains how to serialize and deserialize php to compress complex data types into a single string.

Serialize () encodes variables and their values into text form

Unserialize () restore original variable

$stooges = array('Moe','Larry','Curly');
$new = serialize($stooges);
print_r($new);echo "
";
print_r(unserialize($new));

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)

When the serialized data is placed in a URL and transmitted between pages, you need to call urlencode () to ensure that the URL metacharacters in the URL are processed:

$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);
echo 'urlencode(serialize($shopping)).'">next';

The settings of the margic_quotes_gpc and magic_quotes_runtime parameters affect the data transmitted to unserialize.

If magic_quotes_gpc is enabled, stripslashes () must be used to process the data transmitted in URLs, POST variables, and cookies before Deserialization:

$ New_cart = unserialize (stripslashes ($ cart); // If magic_quotes_gpc is enabled
$ New_cart = unserialize ($ cart );

If magic_quotes_runtime is enabled, you must use addslashes () for processing before writing serialized data to the file, and use stripslashes () for processing before reading them:

// When deserializing an object, PHP automatically calls its wakeUp () method. This allows the object to re-establish various states that are not retained during serialization. For example, database connection.

The above is an in-depth understanding of the serialization and deserialization in php. For more information, see other related articles in the first PHP community!

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.