Php serialization and deserialization details, php deserialization details
Compress complex data types into a string
Serialize () encodes variables and their values into text form
Unserialize () Restore original variable
Eg:
$stooges = array('Moe','Larry','Curly');$new = serialize($stooges);print_r($new);echo "<br />";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 '<a href="next.php?cart='.urlencode(serialize($shopping)).'" rel="external nofollow" >next</a>';
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:
$ Fp = fopen ('/tmp/cart', 'w'); fputs ($ fp, addslashes (serialize ($ a); fclose ($ fp ); // If magic_quotes_runtime is enabled $ new_cat = unserialize (stripslashes (file_get_contents ('/tmp/cart '))); // If magic_quotes_runtime is disabled $ new_cat = unserialize (file_get_contents ('/tmp/cart '));
When magic_quotes_runtime is enabled, the serialized data read from the database must also be processed by stripslashes (). The serialized data saved to the database must be processed by addslashes, in order to be properly stored.
Mysql_query ("insert into cart (id, data) values (1 ,'". addslashes (serialize ($ cart )). "')"); $ rs = mysql_query ('select data from cart where id = 1'); $ ob = mysql_fetch_object ($ rs ); // If magic_quotes_runtime is enabled $ new_cart = unserialize (stripslashes ($ ob-> data); // If magic_quotes_runtime is disabled $ new_cart = unserialize ($ ob-> data );
When an object is deserialized, 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 all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!