json cookies with PHP

本文介绍了一种使用PHP将JSON字符串存储在单个cookie中的方法,以此来替代传统的多个cookie存储方式,节省了带宽并简化了数据管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

json cookies with PHP

I needed to use a cookie to store a hash string so a user would be remembered the next time they come to visit a site. I was required to store their user id (numeric) and also a secret string that gets hashed. This typically would have required two cookies but I didn’t want two cookies. So I did what any one would do: use json to store my data inside of a cookie.

Little do you know, you can set cookies as arrays but it still causes multiple cookies to be made and sent back and forth between the server and the client. So wrapping my id and hash together in a single cookie saves me time and also saves the user some bandwidth, the bandwidth of only one cookie versus two.

So how did I accomplish putting a json string inside of a cookie? I used PHP5′s json_encode function and of course setcookie . The code is short and simple:

[php]
$toCookie = array(“id” => 1, “hash”=>”6b585b736c476e772ee8586957c501254a04917b”);
$json = json_encode($toCookie);
setcookie(“json_cookie”, $json);
[/php]

That was the easy part. Now, how about getting the delicious little guys out? That’s sort of easy, but first, do you know your old friend, get_magic_quotes_gpc , well, if you haven’t met, do it now, because we need his help. A lot of servers have magic quotes turned on, I even had this problem with xampp by default. You have to account for that or your cookie will not be decoded in one piece .

[php]
if (get_magic_quotes_gpc() == true) {
foreach($_COOKIE as $key => $value) {
$_COOKIE[$key] = stripslashes($value);
}
}
[/php]

So now that you’ve cleaned the slashes up, getting the data is easy. Just run json_decode on the cookie. You can decide if you want an object or an array out by passing true as a second argument to get an array.

[php]
$cookie = json_decode($_COOKIE["json_cookie"], true);
var_dump($cookie);
[/php]

Again, it’s not hard and it really does save you from the cookie array syntax mess and also saves the user of having extra cookies.

I hope this helps you to be wise when using cookies.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值