<?php header("Content-type: text/html; charset=utf-8"); $magic = get_magic_quotes_gpc() ? "开启" : "未开启"; $str = array(array('goods_id'=>13,'number'=>1)); setcookie("cart", serialize($str)); echo "magic_quotes_gpc: ".$magic."<br>"; echo $_COOKIE['cart']."<br>"; print_r(unserialize($_COOKIE['cart'])); ?>
原因是magic_quotes_gpc开启时,系统会自动对POST GET COOKIE的结果中的单引号进行转义,加上\,所以$_COOKIE['cart']的值就变成了a:1:{i:0;a:2:{s:8:\"goods_id\";i:13;s:6:\"number\";i:1;}},这样的话unserialize是无法反序列化成功的,就出现了问题.
解决的办法简单来说就是将unserialize($_COOKIE['cart'])改成unserialize(stripslashes($_COOKIE['cart'])),在COOKIE前加上stripslashes,去掉转义符,这样就没问题了.
对于cookie影响我们再做个测试:
1.问题:项目数据需要序列化保存在cookie中,然后再获得cookie的数据反序列,获得原数据,代码如下:
$a[0] = array("key"=>"哈 逻"); $a[1] = array("key"=>"哈 逻"); $jsona = json_encode($a); setcookie("testcookie",""); setcookie("testcookie",$jsona); var_dump($jsona,true); //正常取值 var_dump(json_decode($_COOKIE['testcookie'],true)); //取不到值
2.分析,代码如下:
$a[0] = array("key"=>"哈 逻"); $a[1] = array("key"=>"哈 逻"); $jsona = json_encode($a); var_dump($jsona); //string(50) "[{"key":"\u54c8 \u903b"},{"key":"\u54c8 \u903b"}]" setcookie("testcookie",""); setcookie("testcookie",$jsona); var_dump($_COOKIE['testcookie']); // string(62) "[{\"key\":\"\\u54c8 \\u903b\"},{\"key\":\"\\u54c8 \\u903b\"}]" var_dump(json_decode($_COOKIE['testcookie'],true));
var_dump(json_decode(stripslashes($_COOKIE['testcookie']),true)); var_dump(json_decode(str_replace("\\","",$_COOKIE['testcookie']),true));
① 在开启情况下,处理数据需要stripslashes
② 在没有开启情况下,接受数据先addslashes,处理数据stripslashes
希望本文所述对大家的PHP程序设计有所帮助。