PHP如何对数组进行字符串化处理并存储在Cookie中 [英] PHP how to stringify array and store in cookie

查看:207
本文介绍了PHP如何对数组进行字符串化处理并存储在Cookie中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组

$ value = {array('id'=> $ id,'email'=> $ email,'token'=> $ token)}

我想对数组进行字符串化处理,然后进行编码,然后将其存储在cookie"login"中.你是怎样做的 ?另外,请告诉我如何解码和读取存储的值.

我一直在尝试序列化/反序列化,但是没有按预期工作.例如,

$value = serialize(array('id'=>33, 'email'=>'big@gmail.com', 'token'=>'e9aa0966773d68e0fbf9cb21fc2877b4'));

echo $value; //a:3:{s:2:"id";i:33;s:5:"email";s:20:"big@gmail.com";s:5:"token";s:32:"e9aa0966773d68e0fbf9cb21fc2877b4";}

但是当值进入cookie时,它看起来像这样

a%3A3%3A%7Bs%3A2%3A%22id%22%3Bs%3A1%3A%226%22%3Bs%3A5%3A%22email%22%3Bs%3A20%3A%22craigcosmo%40gmail.com%22%3Bs%3A5%3A%22token%22%3Bs%3A32%3A%22e9aa0966773d68e0fbf9cb21fc2877b4%22%3B%7D

解决方案

有一个序列化/<使用href ="http://www.php.net/unserialize" rel ="noreferrer">反序列化函数将数组转换为字符串并返回.

当您将字符串存储到cookie( setcookie )时,php需要对字符串进行url编码.这样可以防止保存到Cookie中的字符串中的任何字符干扰任何其他标头.当页面下一次加载时,php获取cookie并自动对cookie值进行url解码,以将其返回到其先前的值.至于存储在cookie中的内容,在php中无关紧要,因为php会自动进行url编码/解码.现在,如果您以其他语言(例如javascript)获取Cookie,则可以,您将获得原始字符串.在这种情况下,您可以在JS中使用类似 decodeURI 之类的方法来获取原始值./p>

I got an array like this

$value = {array('id'=>$id, 'email'=>$email, 'token'=>$token)}

I want to stringify the array then encode then store it in cookie "login". How do you do that ? Also please tell me how to decode and read the stored value.

Edit:

I've been trying serialize/unserialize, but it didn't work as expected. for example,

$value = serialize(array('id'=>33, 'email'=>'big@gmail.com', 'token'=>'e9aa0966773d68e0fbf9cb21fc2877b4'));

echo $value; //a:3:{s:2:"id";i:33;s:5:"email";s:20:"big@gmail.com";s:5:"token";s:32:"e9aa0966773d68e0fbf9cb21fc2877b4";}

But when the value go to cookie, it looks like this

a%3A3%3A%7Bs%3A2%3A%22id%22%3Bs%3A1%3A%226%22%3Bs%3A5%3A%22email%22%3Bs%3A20%3A%22craigcosmo%40gmail.com%22%3Bs%3A5%3A%22token%22%3Bs%3A32%3A%22e9aa0966773d68e0fbf9cb21fc2877b4%22%3B%7D

解决方案

there is a serialize/unserialize function to convert an array to a string and back.

Edit: When you store a string to cookie (setcookie), php needs to do a url encode on the string. This prevents any characters in the string saved to cookie interfering with any other headers. When the page is loaded next, php gets the cookie and automatically does a url decode on the cookie value to return it to it's previous value. As far as what is stored in the cookie, this shouldn't matter within php because php will do the url encode/decode automatically. Now if you are getting the cookie in another language such as javascript, then yes, you will get the raw string back. In this case you can use something like decodeURI in JS to get the original value back.

这篇关于PHP如何对数组进行字符串化处理并存储在Cookie中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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