Categories
PHP

Saving Multiple Values in One Cookie

Learn how to store multiple values (array) in one cookie.

Note: Serializing cookies is a security risk because when you unserialize a cookie, the code directly executes on the server. So it is not recommended to serialize/unserialize data with user input. Alternatively, you can use a comma or a combination of unique characters as a delimiter to store multiple values in a cookie. I’ve written an alternate code snippet at the end of this tutorial which uses implode and explode functions to store and restore multiple values in a 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 example, the 20 cookies per domain limit. Therefore, it might make sense to try to save multiple data in one cookie.

PHP allows only strings 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().

<?php
 setcookie('cookiedata', serialize($cookiedata)

Example: Storing multiple values in a cookie with serialize() function

<?php

 if (isset($_COOKIE['data'])) {
  $data = unserialize( $_COOKIE['data'] );
  setcookie('data', '', 1, '/'); // delete cookie 
  
  echo '<b>Cookie read from the user computer</b><pre>';
  print_r($data);
  echo '</pre>Cookie deleted, refresh the page to re-create the cookie.';
 }
 else {
  $data = serialize (['domain' => 'BrainBell.com',
            'category' => 'PHP',
            'subcategory' => 'Cookies and Sessions']);
			
  $expire = time() + 86400 * 30; //30 days 
  setcookie('data',$data, $expire, '/');
  echo 'Cookie created, refresh page to view its values';
 }

The preceding code shows you a different behavior when you refresh the web page. If the cookie is not yet set, the code creates the cookie and sends it to the user’s browser.

When you refresh the page or revisit the same page, it executes the code, deletes the cookie, and prints the saved data.

Example: Using explode and implode functions to store multiple values in a cookie

<?php
 if (! isset($_COOKIE['data'])) {
  $array = ['key1'=>'value1', 'key2'=>'value2', 'key3'=>'value3'];
  $keys = implode('-;-', array_keys($array) );
  $vals = implode('-;-', array_values($array) );
  $data = "$keys:;:$vals";
  
  $expire = time() + 86400 * 30; //30 days 
  setcookie('data',$data, $expire, '/');
  echo 'Cookie created, refresh page to view its values';
 }
 else {
  $data = explode(':;:', $_COOKIE['data']);
  $keys = explode('-;-', $data[0]);
  $vals = explode('-;-', $data[1]);
  $array = array_combine($keys, $vals);
  setcookie('data', '', 1, '/'); // delete cookie 
  
  echo '<b>Cookie reads from the user computer</b><pre>';
   print_r($array);
  echo '</pre>Cookie deleted, refresh the page to re-create the cookie.';
 }

Cookies and Sessions: