background image

php 序列化与反序列化的实例详解

本文介绍下,在

php 中进行序列化与反序列化的方法与实例,有需要的朋友参考下。

php 中实现序列化,可以把复杂的数据类型压缩到一个字符串中。

php 中的序列化与反序列化函数,事下:
serialize() 把变量和它们的值编码成文本形式
unserialize() 恢复原先变量
先来看一个例子:
代码示例

:

<?php
$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 元字符进行处理:
代码示例

:

<?php
$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);
echo '<a href="next.php?cart='.urlencode(serialize($shopping)).'">next</a>';
margic_quotes_gpc 和 magic_quotes_runtime 配置项的设置会影响传递到 unserialize()中的数
据。
如果

magic_quotes_gpc 项是启用的,那么在 URL、POST 变量以及 cookies 中传递的数据在

反序列化之前必须用

stripslashes()进行处理:

代码示例

:

<?php
$new_cart = unserialize(stripslashes($cart)); //如果 magic_quotes_gpc 开启
$new_cart = unserialize($cart);
如 果

magic_quotes_runtime 是 启用 的, 那么 在向 文件 中写 入序 列化 的数 据之 前必 须用

addslashes()进行处理,而在读取它们之前则必须用 stripslashes()进行处理:
代码示例

:

<?php
$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()的处理,以便能