PHP序列化与反序列化的使用

来源:互联网 发布:淘宝店铺复制免费 编辑:程序博客网 时间:2024/06/08 16:57

序列化:将变量转化为可保存或传输的字符串

反序列化:将该字符串在转化为原来的变量使用

作用:存储与传输数据


这样说坑定是蒙了。。。。。。

其实说白了就是将数组改变格式然后存在数据库(使用json_encode与json_decode也可以),就像是我们存储{姓名,年龄,专业}全部打包存储在数据库中,例子如下:

<?php
$arrarray('Moe','Larry','Curly');
$new = serialize($arr);
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传递,代码如下

<?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()处理




3 0
原创粉丝点击