How to Save name:value Pairs as JSON in one Cookie

Two small functions in PHP do the job. For jQuery a small plugin is recommended.

At first the PHP. It does the following:

  • Sets a cookie with an array of name:value pairs in JSON format
  • Deletes an old cookie with the same name
  • Get a value from the JSON cookie but checks also for an old one

Checking for the old cookies could be useful if the code works today with single cookies but you also wanna change smoothly to JSON.

On goabase.net I used the single cookies but more and more features depended on their own single cookie. So it was an ugly view of (up to) 15 single cookies with small values like 0, 1, „de“, „sticky“ everytime I opened Firebug or similar…

Idea was to get someting like that:
example json

And the solution should be self explaining:

<?php
/**
 * Sets and fills the cookie 'container' with json name:value
 * If the value is empty, it deletes the name:val pair
 *
 * @param $array - name => value
 *               We use an array because of multiple settings on one page,
 *               e.g. options from radiobuttons after the submit
 * @return string - value
 */
function setCookieJson($arr) {

   if($arr) {
      // we don't need old cookies anymore
      foreach ($arr as $name => $val) {
         if(isset($_COOKIE[$name])) {
            setcookie($name,null,1);
         }
      }

      // the cookie which saves the json
      if ($_COOKIE['container']) {
         // read the json
         $data = json_decode($_COOKIE['container'],true);

         // to delete unwanted
         foreach ($data as $index => $item) {
            if(isset($arr[$index]) && $arr[$index] === '') {
            unset($data[$index],$arr[$index]);
            }
         }

         // merge them
         $arr = array_merge($data,$arr);
      }

      setcookie('container',json_encode($arr),time() + 31536000);
   }
}

/**
 * Get the value from the json-cookie
 * Returns old one, if there is any
 *
 * @param $name - element name
 * @return mixed - the value
 */
function getCookieJson($name) {

   // read the container cookie
   $data = json_decode($_COOKIE['container'],true);

   if(isset($data[$name])) {
      return $data[$name];
   }
   // nothing found
   else {
      // check for old cookie
      return $_COOKIE[$name];
   }
}

 

Usage is easy:

<?php 
// examples
$my_cookie['foo'] = 'bar';
$my_cookie['foobar'] = 'foobar';

// set
setCookieJson($my_cookie); // {"foo":"bar","foobar":"foobar"}

// get
$cookie_foo = getCookieJson('foo'); // bar

// delete
$my_cookie['foobar'] = '';
setCookieJson($my_cookie); // {"foo":"bar"}

 

To get it in a similar way with jQuery the plugin js-cookie is recommended: https://github.com/js-cookie/js-cookie

The functions with it:

<script>
function setCookieJson(e,v) {
    var cn = 'container'; // name of the cookie
    var data = Cookies.get(cn);

    // first time we have to create
    if (!data) {
        Cookies.set(cn, '{"'+e+'":"'+v+'"}');
    }
    else {
        // cookie is defined, so wie parse it
        data = jQuery.parseJSON(data);

        // delete if 0
        if(v == 0)
            delete data[e];
        else
            data[e] = v;

        // write it
        Cookies.set(cn,data);
    }
}

function getCookieJson(e) {
    var val;
    var data = Cookies.get('container');
    
    if (data) {
        data = jQuery.parseJSON(data);
        val = data[e];
    }
    // try to read the old
    if(!val) {
        val = Cookies.get(e);
    }
    return val;
}
</script>

Example:

<script>
setCookieJson('foo','bar'); 
var val = getCookieJson('foo'); // bar
console.log(val);
</script>

 
 
That’s all. Maybe it’s usefull for you.

Schreibe einen Kommentar