在cookie中存储阵列 [英] Storing arrays in cookies

查看:155
本文介绍了在cookie中存储阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些数组数据存储在cookie中,我一直在研究这样做的最佳方式,许多人似乎用说连载是要走的路,但在这个线程:

I need to store some array data in a cookie and I have been researching the best way to do it, many people seem to say using serialize is the way to go, but then in this thread:

PHP如何在字符串化饼干阵列和存储

..有人建议反对使用它作为连载将调用序列化类的构造函数,这是不好的,因为它可以导致code的执行。

..someone suggested against using it as "serialize will call constructor of a serialized class. This is bad because it can cause code execution."

所以我不知道我有什么其他选择?关于 base64_en code

So I'm wondering what other options I have? What about base64_encode?

我不能使用会议,因为我需要后,浏览器关闭时保留数据;虽然我也很担心饼干 4KB 限制。

I can't use sessions as I need to retain the data AFTER the browser is closed; though I am also worried about Cookies 4KB limit.

FWIW我的存储中存储的内容某人的购物车购物车数据,它需要被装回在他们的车,当他们回来。

FWIW I am storing shopping cart data of what is stored in someones cart, it needs to be loaded back in their cart when they come back.

推荐答案

如何生成一个唯一的ID,将其存储在cookie中,存储您的序列化阵列和数据库中的ID?

How about generating a unique ID, storing it in a cookie, and storing your serialized array and the ID in database?

例如:

// ------------ STORING TO COOKIE AND DATABASE ------------ //
$id = uniqid();
setcookie("id", $id, time()+60*60*24); // 1 day

$serialized = serialize($array);
mysql_query("INSERT INTO yourTable (id, array) VALUES ('$id', '$serialized')");


// ------------ SELECTING FROM DATABASE ------------ //
if(!isset($_COOKIE['id'])) die();
$id = mysql_real_escape_string($_COOKIE['id']);

$result = mysql_query("SELECT array FROM yourTable WHERE id = $id LIMIT 1");
if(!is_resource($result)) die();
$serialized = mysql_result($result, 0);
$array = unserialize($serialized);

这篇关于在cookie中存储阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆