4

I need to store some array data in a cookie and I have been researching the best way to do it, many people seem to say using serialize is the way to go, but then in this thread:

PHP how to stringify array and store in cookie

..someone suggested against using it as "serialize will call constructor of a serialized class. This is bad because it can cause code execution."

So I'm wondering what other options I have? What about base64_encode?

I can't use sessions as I need to retain the data AFTER the browser is closed; though I am also worried about Cookies 4KB limit.

FWIW I am storing shopping cart data of what is stored in someones cart, it needs to be loaded back in their cart when they come back.

Community
  • 1
  • 1
Brett
  • 19,449
  • 54
  • 157
  • 290

3 Answers3

5

How about generating a unique ID, storing it in a cookie, and storing your serialized array and the ID in database?

Example:

// ------------ STORING TO COOKIE AND DATABASE ------------ //
$id = uniqid();
setcookie("id", $id, time()+60*60*24); // 1 day

$serialized = serialize($array);
mysql_query("INSERT INTO yourTable (id, array) VALUES ('$id', '$serialized')");


// ------------ SELECTING FROM DATABASE ------------ //
if(!isset($_COOKIE['id'])) die();
$id = mysql_real_escape_string($_COOKIE['id']);

$result = mysql_query("SELECT array FROM yourTable WHERE id = $id LIMIT 1");
if(!is_resource($result)) die();
$serialized = mysql_result($result, 0);
$array = unserialize($serialized);
Nikola K.
  • 7,093
  • 13
  • 31
  • 39
  • 1
    +1 , seems to be the best solution as it's highly advisable not to use cookies to store things other than identification or minor settings. – Adi Jul 08 '12 at 11:04
4

Expanding on previous comments and answrs, you should try really hard to avoid data being stored in a cookie, as opposed to a pointer to data, such as an ID to a database row.

Assuming, that all clients are enemies (which I think to be reasonable assumption), a wrong cookie - be it malicious or simply buggy - will be unable to do much harm, if it only contains a pointer:

  • Invalid: Silently drop it
  • Wrong: Check by comparing ID to the user, who is requesting it; Silently drop it if so
  • Valid; use it

I peronally prefer silent dropping to error messages, as I have the gut feeling, that this might make it harder for the very few really malicious users out there.

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
0

Cookie it is not best way store user data Users must be authorized on your site, and all data must be stored in database by user_id

Andrey Vorobyev
  • 896
  • 1
  • 10
  • 37