php中序列化与反序列化详解

黄舟
发布: 2023-03-06 12:14:01
原创
1303 人浏览过

本文介绍了php中序列化与反序列化的相关知识。具有很好的参考价值,下面跟着小编一起来看下吧

把复杂的数据类型压缩到一个字符串中

serialize() 把变量和它们的值编码成文本形式

unserialize() 恢复原先变量

eg:

$stooges = array('Moe','Larry','Curly');
$new = serialize($stooges);
print_r($new);echo "<br />";
print_r(unserialize($new));
登录后复制

结果:a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}

Array ( [0] => Moe [1] => Larry [2] => Curly )

当把这些序列化的数据放在URL中在页面之间会传递时,需要对这些数据调用urlencode(),以确保在其中的URL元字符进行处理:

$shopping = array(&#39;Poppy seed bagel&#39; => 2,&#39;Plain Bagel&#39; =>1,&#39;Lox&#39; =>4);
echo &#39;<a href="next.php?cart=&#39;.urlencode(serialize($shopping)).&#39;" rel="external nofollow" >next</a>&#39;;
登录后复制

margic_quotes_gpc和magic_quotes_runtime配置项的设置会影响传递到unserialize()中的数据。

如果magic_quotes_gpc项是启用的,那么在URL、POST变量以及cookies中传递的数据在反序列化之前必须用stripslashes()进行处理:

$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc开启
$new_cart = unserialize($cart);
登录后复制

如果magic_quotes_runtime是启用的,那么在向文件中写入序列化的数据之前必须用addslashes()进行处理,而在读取它们之前则必须用stripslashes()进行处理:

$fp = fopen(&#39;/tmp/cart&#39;,&#39;w&#39;);
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//如果magic_quotes_runtime开启
$new_cat = unserialize(stripslashes(file_get_contents(&#39;/tmp/cart&#39;)));
//如果magic_quotes_runtime关闭
$new_cat = unserialize(file_get_contents(&#39;/tmp/cart&#39;));
登录后复制

在启用了magic_quotes_runtime的情况下,从数据库中读取序列化的数据也必须经过stripslashes()的处理,保存到数据库中的序列化数据必须要经过addslashes()的处理,以便能够适当地存储。

mysql_query("insert into cart(id,data) values(1,&#39;".addslashes(serialize($cart))."&#39;)");
$rs = mysql_query(&#39;select data from cart where id=1&#39;);
$ob = mysql_fetch_object($rs);
//如果magic_quotes_runtime开启
$new_cart = unserialize(stripslashes($ob->data));
//如果magic_quotes_runtime关闭
$new_cart = unserialize($ob->data);
登录后复制

当对一个对象进行反序列化操作时,PHP会自动地调用其__wakeUp()方法。这样就使得对象能够重新建立起序列化时未能保留的各种状态。例如:数据库连接等。

 以上就是php中序列化与反序列化详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!