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

yipeiwu_com5年前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('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);
echo '<a href="next.php?cart='.urlencode(serialize($shopping)).'" rel="external nofollow" >next</a>';

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('/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);

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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持【宜配屋www.yipeiwu.com】!

相关文章

php 删除无限级目录与文件代码共享

<? //删除目录 class del_path { function wm_chief_delpath($del_path) { if(!file_exists($del_pat...

PHP变量的定义、可变变量、变量引用、销毁方法

复制代码 代码如下:<?php$long="big_long_variable_name";$$long="PHP";     /...

php中$_POST与php://input的区别实例分析

本文实例分析了php中$_POST与php://input的区别。分享给大家供大家参考。具体分析如下: $_POST 与 php教程://input可以取到值,$HTTP_RAW_POS...

PHP实现通过CURL上传文件功能示例

本文实例讲述了PHP实现通过CURL上传文件功能。分享给大家供大家参考,具体如下: PHP使用CURL上传文件只需发送一个POST请求就可以了,在请求中设置某个字段为需要上传的文件全路径...

PHP实现在数据库百万条数据中随机获取20条记录的方法

本文实例讲述了PHP实现在数据库百万条数据中随机获取20条记录的方法。分享给大家供大家参考,具体如下: 额,为什么要写这个? 在去某个公司面试时,让写个算法出来,当时就蒙了,我开发过程中...