博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
php中序列化与反序列化
阅读量:6984 次
发布时间:2019-06-27

本文共 1676 字,大约阅读时间需要 5 分钟。

http://www.cnblogs.com/A-Song/archive/2011/12/13/2285619.html

转自:

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

serialize() 把变量和它们的值编码成文本形式
unserialize() 恢复原先变量
eg:
$stooges = array('Moe','Larry','Curly'); $new = serialize($stooges); print_r($new);echo "
"; 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 'next';
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()方法。这样就使得对象能够重新建立起序列化时未能保留的各种状态。例如:数据库连接等。

转载于:https://www.cnblogs.com/kenshinobiy/p/4389474.html

你可能感兴趣的文章
POJ NOI0105-45 金币
查看>>
Project Euler Problem 15 Lattice paths
查看>>
组合模式
查看>>
Python之路番外(第三篇):Pycharm的使用秘籍
查看>>
alpha冲刺9
查看>>
Hibernate组件映射
查看>>
转:目标检测算法总结
查看>>
springmvc @valid
查看>>
抓包工具 - Fiddler - (三)
查看>>
使用Hibernate注解 @Transient
查看>>
【POJ3294】 Life Forms(SA)
查看>>
让思路更清晰——我是怎样使用思维导图的
查看>>
nohup
查看>>
iTextSharp生成pdf的一个简单例子
查看>>
php操作Access数据库
查看>>
【原译】一个可定制的WPF任务对话框
查看>>
zabbix agent 类型自带的key
查看>>
转:sql篇 select from where group by having order by
查看>>
Leangoo如何颠覆传统项目管理软件?
查看>>
GCD中有哪几种Queue?你自己建立过串行Queue吗?背后的线程模型是什么样的
查看>>