Storing nested arrays in a cookie

I am trying to store nested arrays in a cookie. I decided to save the array as a JSON string. However, I get this warning:

PHP Warning: cookie values ​​cannot contain any of the following values:,; \ t \ r \ n \ 013 \ 014 'in foobar.php

Is there a recommended way to store nested arrays in a cookie?

+6
php cookies
source share
5 answers

You can use base64_encode() and base64_decode()

Please note that according to the manual:

Basic 64-encoded data takes up about 33% more space than the original data.

+3
source share

If you have another form of saving available (db, sessions, memcache), I would recommend storing real data there. Then put a unique identifier in the cookie, which you can use to find the data you need. It is much cleaner and safer.

+2
source share

Is there a recommended way to store nested arrays in a cookie?

Yes - no. Store it on the server using a session or other descriptor. Not only are formatting and storage issues stored in cookies, but file size is also limited.

FROM.

+2
source share

I don't think this is a clean way to do this, but you could urlencode json_encode d string to save it in a cookie.

Edit: Tom Haigh's path is definitely cleaner (using base64_encode).

+1
source share
 $array = array(); $array[] = array(1,2,3); $array[] = array('a','b','c'); setcookie("test",serialize($array)); 

Just serialize, works great.

You will receive this in your cookie:

 'test' => string 'a:2:{i:0;a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}i:1;a:3:{i:0;s:1:"a";i:1;s:1:"b";i:2;s:1:"c";}}' (length=86) 
0
source share

All Articles