Cookie多个值 [英] Cookie multiple values
问题描述
在php手册的 cookies部分中,它指出您可以通过在cookie名称中简单地添加 []来为单个cookie添加多个值。
In the php manual under section "cookies" it states that you can add multiple values to a single cookie by simply adding a '[]' to the cookie name.
起初,我对此的理解是:
At first my understanding of this was to do the following:
<?php
setcookie("[user1]", "bill");
setcookie("[user2]", "tom");
print_r($_COOKIE);
?>
输出结果是:'Array()'
显然看到一个空数组我知道有些事情不对,但是我遵循了手册中的规定。因此,我在浏览器中进入开发人员模式,以查看浏览器和服务器的所有标头信息。
and the out put was: 'Array ( )' Obviously after seeing an empty array I knew something was not right but, I had followed what the manual had stated. So I went in developer mode in the browser to see all header information of the browser and server.
浏览器和服务器都具有以下内容:
[user1] = bill
[user2] = tom
Browser and Server both had the following: [user1]=bill [user2]=tom
但是$ _COOKIE关联数组为空,即'Array()'
yet the $_COOKIE associative array was empty i.e. 'Array()'
所以我在PHP手册下研究并发现了存储多个值的方式在外部来源的变量部分的单个Cookie中。
So I researched and found under the PHP manual the way several values are stored in a single cookie under section, 'Variables From External Sources.'
此处提供了如何正确完成此操作的详细示例。代替上面的方法,它是这样完成的:
Here it gives a detailed example of how this is correctly done. Instead of the above, it is done as follows:
<?php
setcookie("Cookie[user1]", "bill");
setcookie("Cookie[user2]", "tom");
print_r($_COOKIE);
?>
上述脚本的输出为:'Array([Cookie] => Array([user1] = > bill [user2] => tom))'
Output for the above script is: 'Array ( [Cookie] => Array ( [user1] => bill [user2] => tom ) ) '
我的问题是,为什么在第一个示例中注册cookie却不打印,而在第二个示例中是正确的示例,它们是否确实在$ _COOKIE变量中打印出来了?
My question is why in the first example do the cookies register and yet don't print out but in the second (correct) example they do print out in the $_COOKIE variable?
推荐答案
您的操作略有错误
setcookie("Cookie[user1]", "bill");
setcookie("Cookie[user2]", "tom");
这将存储 bill值;并在名为 Cookie的Cookie中添加 tom作为数组,可通过$ _COOKIE supoer全局访问该Cookie。
,您需要像这样访问它:
This will store the values 'bill; and 'tom' as an array, inside a cookie called 'Cookie', which is accessed via the $_COOKIE supoer global. you need to access it like this:
print_r($_COOKIE['Cookie']); // Cookie is the name you used above
上方使用的名称。
另一个示例:
Another example:
setcookie("bob[user1]", "bill"); // cookie name is bob
print_r($_COOKIE['bob']); // Notice the cookie name is the key here
如果要在单个cookie中存储数组您还可以序列化内容。这样会将数组转换为要存储在Cookie中的字符串,然后可以在需要数据时将其转换回去。
If you want to store an array inside a single cookie you can also serialize the contents. This will convert the array to a string to be stored inside the cookie, you can then convert it back when you need the data.
$myArray = array(1,2,3,4);
setCookie('my_cookie', serialize($myArray)); // Store the array as a string
$myArray = unserialize($_COOKIE['my_cookie]); // get our array back from the cookie
这篇关于Cookie多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!