Question

I'm using the following functions to set an array of values in a cookie in PHP, but I also need an "add" and "edit" function - any suggestions on how I can do that?

function build_cookie($var_array) {
  if (is_array($var_array)) {
    foreach ($var_array as $index => $data) {
      $out.= ($data!="") ? $index."=".$data."|" : "";
    }
  }
  return rtrim($out,"|");
}

function break_cookie ($cookie_string) {
  $array=explode("|",$cookie_string);
  foreach ($array as $i=>$stuff) {
    $stuff=explode("=",$stuff);
    $array[$stuff[0]]=$stuff[1];
    unset($array[$i]);
  }
  return $array;
}

Usage:

setcookie("mycookies", build_cookie($cookies_array), time()+60*60*24*30);

$cookies_array2 = break_cookie(urldecode($_COOKIE['mycookies']));

    foreach ($cookies_array2 as $k => $v) {
        echo "$k : $v <br />\n";
    }
Was it helpful?

Solution

One thing that you should consider using is serialize and unserialize to encode your cookie data. Just be careful though, from my experience you have to use stripslashes on the cookie value before you unserialize it. This way you can unserialize the data, change the values, reserialize the cookie and send it again. Serialize will make it easier in the future if you want to store more complex data types.

for example:

setcookie("mycookies",serialize($cookies_array),time()+60*60*24*30);

// This won't work until the next page reload, because $_COOKIE['mycookies']
// Will not be set until the headers are sent    
$cookie_data = unserialize(stripslashes($_COOKIE['mycookies']));
$cookie_data['foo'] = 'bar';
setcookie("mycookies",serialize($cookies_array),time()+60*60*24*30);

OTHER TIPS

I would store just an id in the cookie and use a flat file (ini, serialized or plain text) or database to store the values. The thing is - cookie are severely space-limited and you should add as little as possible. One one of my latest projects i had to store alot of information and, since i had access to ssd drives, i put the arrays and objects serialized in zipped files and in the cookies i saved the id, and then some hashes of varios parts of the data to be able to do some quick validation.

And, from a security point of view, having just an id (and a hash of the local data so one can't easily change the id or some other form of verification of that id) is more secure than putting the data in the cookie.

Do you have any special reason to save data as cookies?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top