Home  >  Article  >  Backend Development  >  Serialization and deserialization in php

Serialization and deserialization in php

高洛峰
高洛峰Original
2017-02-18 17:07:49815browse

Compress complex data types into a string

serialize() Encode variables and their values ​​into text form

unserialize() Restore the original variables

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 these serialized data are placed in the URL and passed between pages, urlencode() needs to be called on the data to ensure that the URL metacharacters in it are processed:


$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);
echo '<a href="next.php?cart=&#39;.urlencode(serialize($shopping)).&#39;">next</a>';

The settings of the margic_quotes_gpc and magic_quotes_runtime configuration items will affect the data passed to unserialize().

If the magic_quotes_gpc item is enabled, data passed in URLs, POST variables, and cookies must be processed with stripslashes() before deserialization:


$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc开启
$new_cart = unserialize($cart);

If magic_quotes_runtime is enabled, serialized data must be processed with addslashes() before writing it to the file, and before reading it. Use stripslashes() for processing:

$fp = fopen('/tmp/cart','w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//如果magic_quotes_runtime开启
$new_cat = unserialize(stripslashes(file_get_contents('/tmp/cart')));
//如果magic_quotes_runtime关闭
$new_cat = unserialize(file_get_contents('/tmp/cart'));
在启用了magic_quotes_runtime的情况下,从数据库中读取序列化的数据也必须经过stripslashes()的处理,保存到数据库中的序列化数据必须要经过addslashes()的处理,以便能够适当地存储。
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);
//如果magic_quotes_runtime开启
$new_cart = unserialize(stripslashes($ob->data));
//如果magic_quotes_runtime关闭
$new_cart = unserialize($ob->data);

When deserializing an object, PHP will automatically call its __wakeUp() method. This allows the object to re-establish various states that were not preserved during serialization. For example: database connection, etc.

For more articles related to serialization and deserialization in php, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn