To store the array values in cookie, first you need to convert them to string, so here is some options.
Storing cookies as JSON
Storing code
setcookie('your_cookie_name', json_encode($info), time()+3600);
Reading code
$data = json_decode($_COOKIE['your_cookie_name'], true);
JSON can be good choose also if you need read cookie in front end with JavaScript.
Actually you can use any encrypt_array_to_string
/decrypt_array_from_string
methods group that will convert array to string and convert string back to same array.
For example you can also use explode
/implode
for array of integers.
Warning: Do not use serialize/unserialize
From PHP.net
Do not pass untrusted user input to unserialize().
- Anything that coming by HTTP including cookies is untrusted!
References related to security
As an alternative solution, you can do it also without converting array to string.
setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);
And after if you will print $_COOKIE
variable, you will see the following
echo '<pre>';
print_r( $_COOKIE );
die();
Array
(
[my_array] => Array
(
[0] => value1
[1] => value2
[2] => value3
)
)
This is documented PHP feature.
From PHP.net
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…