views:

286

answers:

3

First off, I'm not all that familiar with cookies but I know how they work. I've seen quite a few different tutorials with plain PHP code but I'm looking for a solid example of how to store arrays in a cookie using the symfony syntax:

$this->getResponse()->setCookie('myCookie', $data);

You can't just pass in an array since it expects a string. Is the only way to do it to serialize an array first?

Are there any other options while storing data in a cookie?

+3  A: 

You should probably store the data in a session, rather than a cookie.

PHP supports this automatically; just place your data in $_SESSION['key'], and it will persist across page loads by that user.

Behind the scenes, PHP sets a PHPSESSID cookie on the client, and uses this to look up data on your web server. This has two distinct benefits over using cookies.

  1. The data can’t be tampered with. Cookies can be changed, deleted, and otherwise mangled by the client. You shouldn’t use them to store important information.
  2. Your storage is unlimited.
  3. You have different options for session data storage. They can go on disk, or into memcache, or whatever.
  4. You can store complex types like arrays, or even object instances.

See the PHP documentation on sessions for more.

ieure
+1  A: 

You can transform the array to a set of key/values in your cookie in case the array is the only subject to store :

$this->getResponse()->setCookie('myCookie[0]', $data1);
$this->getResponse()->setCookie('myCookie[1]', $data2);
Theo.T
A: 

If you really need to store it in a cookie and not in a session, you can use serialization:

$this->getResponse()->setCookie('myCookie', serialize($data));

$data = unserialize($this->getRequest()->getCookie('myCookie'));
laurentb