Compress complex data types into a string
serialize() Encode variables and their values into text form
unserialize() Restore original variables
<span style="color: #800080">$stooges = <span style="color: #0000ff"><a href="//m.sbmmt.com/wiki/1041.html" target="_blank">array</a>('Moe','Larry','Curly');<br/><span style="color: #800080">$<a href="//m.sbmmt.com/wiki/165.html" target="_blank">new</a> = <span style="color: #008080">serialize(<span style="color: #800080">$stooges);<br/><span style="color: #008080"><a href="//m.sbmmt.com/wiki/1362.html" target="_blank">print</a>_r(<span style="color: #800080">$new);<span style="color: #0000ff"><a href="//m.sbmmt.com/wiki/1343.html" target="_blank">echo</a> "<br />";<br/><span style="color: #008080">print_r(<span style="color: #008080">unserialize(<span style="color: #800080">$new));</span></span></span></span></span></span></span></span></span></span></span>
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, they will be passed between pages. , you need to call urlencode() on this data to ensure that the URL metacharacters in it are processed:
<span style="color: #800080">$shopping = <span style="color: #0000ff">array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);<br/><span style="color: #0000ff">echo '<a href="next.php?cart='.<span style="color: #008080">urlencode(<span style="color: #008080">serialize(<span style="color: #800080">$shopping)).'">next</a>';</span></span></span></span></span></span>
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:
<span style="color: #800080">$new_cart = <span style="color: #008080">unserialize(<span style="color: #008080">stripslashes(<span style="color: #800080">$cart)); <span style="color: #008000">//<span style="color: #008000">如果magic_quotes_gpc开启<span style="color: #008000"><br/><span style="color: #800080">$new_cart = <span style="color: #008080">unserialize(<span style="color: #800080">$cart);</span></span></span></span></span></span></span></span></span></span>
If magic_quotes_runtime is enabled , then serialized data must be processed with addslashes() before writing to the file, and stripslashes() before reading them:
//当对一个对象进行反序列化操作时,PHP会自动地调用其wakeUp()方法。这样就使得对象能够重新建立起序列化时未能保留的各种状态。例如:数据库连接等。
The above is the detailed content of In-depth understanding of serialization and deserialization in php. For more information, please follow other related articles on the PHP Chinese website!