问题
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);
?>
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.
Browser and Server both had the following: [user1]=bill [user2]=tom
yet the $_COOKIE associative array was empty i.e. 'Array()'
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);
?>
Output for the above script is: 'Array ( [Cookie] => Array ( [user1] => bill [user2] => tom ) ) '
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?
回答1:
You are doing it slightly incorrectly
setcookie("Cookie[user1]", "bill");
setcookie("Cookie[user2]", "tom");
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
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
来源:https://stackoverflow.com/questions/13339054/cookie-multiple-values