Search code examples
phpcookiessetcookie

How to add / edit a cookie in php?


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";
    }

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);