PHP序列化与反序列化的使用
2016-04-10 11:06
555 查看
序列化:将变量转化为可保存或传输的字符串
反序列化:将该字符串在转化为原来的变量使用
作用:存储与传输数据
这样说坑定是蒙了。。。。。。
其实说白了就是将数组改变格式然后存在数据库(使用json_encode与json_decode也可以),就像是我们存储{姓名,年龄,专业}全部打包存储在数据库中,例子如下:
结果如下:
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传递,代码如下
nextArray
( [haha] => 2 [hehe] => 1 [heihei] => 4 )
注:其中next为:
xx/next.php?test=a%3A3%3A%7Bs%3A4%3A%22haha%22%3Bi%3A2%3Bs%3A4%3A%22hehe%22%3Bi%3A1%3Bs%3A6%3A%22heihei%22%3Bi%3A4%3B%7D
你看上面是不是很像我们平时浏览的网页啊
另外注意在margic_quotes_gpc与magic_quotes_runtime开启的情况下会影响到unnserialize的传输,解决办法如下:
<span style="font-size:12px;">$new_str = unserialize(stripslashes($str));</span><span style="font-size: 10px;">
</span>
注:margic_quotes_gpc开启需要在其反序列化时stripslashes
$fp = fopen('/tmp/str','w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//如果magic_quotes_runtime开启
$new_str = unserialize(stripslashes(file_get_contents('/tmp/str')));
//如果magic_quotes_runtime关闭
$new_str = unserialize(file_get_contents('/tmp/str'));注:如果magic_quotes_runtime开启需要在写入文件前addslashes()处理,读取时stripslashes()处理
反序列化:将该字符串在转化为原来的变量使用
作用:存储与传输数据
这样说坑定是蒙了。。。。。。
其实说白了就是将数组改变格式然后存在数据库(使用json_encode与json_decode也可以),就像是我们存储{姓名,年龄,专业}全部打包存储在数据库中,例子如下:
结果如下:
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传递,代码如下
<?php $shopping = array('haha' => 2,'hehe' =>1,'heihei' =>4); echo '<a href="next.php?test='.urlencode(serialize($shopping)).'">next</a>'; $t1 = urlencode(serialize($shopping)); $t2 = urldecode($t1); //将传过来的数据解析回去 print_r(unserialize($t2));//将传来的数据解析回去结果如下:
nextArray
( [haha] => 2 [hehe] => 1 [heihei] => 4 )
注:其中next为:
xx/next.php?test=a%3A3%3A%7Bs%3A4%3A%22haha%22%3Bi%3A2%3Bs%3A4%3A%22hehe%22%3Bi%3A1%3Bs%3A6%3A%22heihei%22%3Bi%3A4%3B%7D
你看上面是不是很像我们平时浏览的网页啊
另外注意在margic_quotes_gpc与magic_quotes_runtime开启的情况下会影响到unnserialize的传输,解决办法如下:
<span style="font-size:12px;">$new_str = unserialize(stripslashes($str));</span><span style="font-size: 10px;">
</span>
注:margic_quotes_gpc开启需要在其反序列化时stripslashes
$fp = fopen('/tmp/str','w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//如果magic_quotes_runtime开启
$new_str = unserialize(stripslashes(file_get_contents('/tmp/str')));
//如果magic_quotes_runtime关闭
$new_str = unserialize(file_get_contents('/tmp/str'));注:如果magic_quotes_runtime开启需要在写入文件前addslashes()处理,读取时stripslashes()处理
相关文章推荐
- PHP文件处理的高级应用
- php输出echo、print、print_r、printf、sprintf、var_dump比较
- PHP 相关配置
- zend stuido 12.5的插件安装和xdebug调试器的配置和和配置注意
- php基础留言板的注意细节(使用txt做简单的数据库)。
- php_D3_“简易聊天室 ”实现的关键技术 详解
- PHP设计模式——訪问者模式
- php去掉字符串的最后一个字符附substr()和mb_substr()的用法
- Wamp mysql启动不了,phpAdmin显示#2002无法连接服务器
- php实现生成验证码实例分享
- PHP isset()与empty()的使用区别详解
- yii2使用相关记录
- php5.6 一键编译
- ntpdate -u ntp.api.bz
- PHP中 应该如何写 无符号右移
- 查看PHP代码执行的时间
- 010.php位运算和位移运算
- 008.php运算符
- 007.php数据类型转换即$_GET[]
- lftp的用法