PHP

Saving Multiple Data in One Cookie

Usually, one cookie has one value: one string. Therefore, to store multiple data in cookies, multiple cookies have to be used. This, however, could create some problems, for instance the 20 cookies per domain limit. Therefore, it might make sense to try to save multiple data in one cookie. For this, an array comes to mind.

setcookie('cookiedata', serialize($cookiedata)

However, only strings are allowed for the value of a cookie. Therefore, the array must be transformed into a string using serialize() and can then be converted back into an array using unserialize().

Helper Library to Save Multiple Values into One Cookie
<?php
  require_once 'stripCookieSlashes.inc.php';
  function setCookieData($arr) {
    $cookiedata = getAllCookieData();
    if ($cookiedata == null) {
      $cookiedata = array();
    }
    foreach ($arr as $name => $value) {
      $cookiedata[$name] = $value;
    }
    setcookie('cookiedata',
      serialize($cookiedata),
      time() + 30*24*60*60);
  }
  function getAllCookieData() {
    if (isset($_COOKIE['cookiedata'])) {
      $formdata = $_COOKIE['cookiedata'];
      if ($formdata != '') {
        return unserialize($formdata);
      } else {
        return array();
      }
    } else {
      return null;
    }
  }
  function getCookieData($name) {
    $cookiedata = getAllCookieData();
    if ($cookiedata != null &&
      isset($cookiedata[$name])) {
        return $cookiedata[$name];
      }
    }
    return '';
  }
?>

For this, you can write a library that is quite similar to the library used in the previous chapter to save form data in a cookie. One cookie called cookiedata contains all values as an associative array. The function getCookieData() returns one specific value, whereas setCookieData() takes an array and writes its contents to the cookie. The preceding listing shows the complete code for this library.

The following listing uses this library to implement the cookie test from the previous coding using this library.

<?php
  require_once 'getCookieData.inc.php';
  if (isset($_GET['step']) && $_GET['step'] == '2')
{
    $test = (getCookieData('test') == 'ok') ?
      'supports' : 'does not support';
    echo "Browser $test cookies.";
  } else {
    setCookieData(array('test' => 'ok'));
    header("Location:
{$_SERVER['PHP_SELF']}?step=2");
  }
?>
by BrainBellupdated
Advertisement: