tags:

views:

162

answers:

5

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

PHP Warning: Cookie values can not contain any of the following ',; \t\r\n\013\014' in foobar.php

Is there a recommended way of storing nested arrays in a cookie?

+2  A: 

You could use base64_encode() and base64_decode()

Note that according to the manual:

Base64-encoded data takes about 33% more space than the original data.

Tom Haigh
This seems to work for me.
morpheous
+1  A: 

I don't think that's a clean way to do it, but you could urlencode the json_encoded string to be able to store it in a cookie.

Edit: Tom Haigh way is certainly cleaner (using base64_encode).

p4bl0
This is a common approach. `rawurlencode` might be a better bet if you want to read the cookie from elsewhere, eg. JavaScript's `decodeURIComponent`.
bobince
A: 
$array = array();
$array[] = array(1,2,3);
$array[] = array('a','b','c');
setcookie("test",serialize($array));

Just serialize, works just fine.

You get that 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)
Mikushi
the danger of this is that you then are unserializing user-submitted data, which is potentially dangerous as by passing a different string people could instantiate arbitrary objects etc.
Tom Haigh
Totally agree with that. Not very secure, just depends what kind of data your storing in that cookie. If it's sensible, you can obfuscate/encrypt it with a private key.
Mikushi
Also that does appear to have loads of semicolons in, which would surely cause `Set-Cookie` to fail?
bobince
@Mikushi: "just depends what kind of data your storing in that cookie". No - you miss my point. Regardless of what data is there you are unserializing user-submitted data, which can let people muck around with what variables/objects are being created in your php script
Tom Haigh
This is a very simple example, the developer should always validate user input, Cookie included. I was just answering the "how to put nested array in a cookie", after all, doing so it's just a bad practice anyway, you should reduce as much as possible the informations you're storing on the user computer, that's just not safe like you mention.
Mikushi
+2  A: 

If you have some other form of persistence available (db, sessions, memcache), I'd recommend storing the real data there. Then put a unique identifier in the cookie, which can be used to look up the desired data. It's just a lot cleaner and more secure.

grossvogel
+2  A: 

Is there a recommended way of storing nested arrays in a cookie?

Yes - don't. Store it serverside using a session or other handle. Not only are there formatting and scope issues with storing data in cookies, there's also a file size limt.

C.

symcbean