Return to Snippet

Revision: 35115
at November 2, 2010 21:09 by liamchapman


Updated Code
<?php
/**
 * Store an array inside a cookie as a JSON String
 * Useful for passing large bits of data :)
 * @author LiamC
 * @param $var = cookie value
 * @param $limit = size limit. default and max size for a cookie is 4kb.
**/
function cookieArray($var, $limit=4096, $cookie_name="my_cookie")
{
	//check if we have cookie
	if($_COOKIE[$cookie_name])
	{
		
		//decode cookie string from JSON
		$cookieArr = (array) json_decode($_COOKIE[$cookie_name]);							
		
		//push additional data
		array_push($cookieArr, $var);
		
		//remove empty values
		foreach($cookieArr as $k => $v){ if($v == '' || is_null($v) || $v == 0){ unset($cookieArr[$k]); } }
		
		//encode data again for cookie
		$cookie_data = json_encode($cookieArr);
		
		//need to limit cookie size. Default is set to 4Kb. If it is greater than limit. it then gets reset.
		$cookie_data = mb_strlen($cookie_data) >= $limit ? '' : $cookie_data;
		
		//destroy cookie
		setcookie($cookie_name, '', time()-3600 , '/');
		
		//set cookie with new data and expires after a week
		setcookie($cookie_name, $cookie_data, time()+(3600*24*7) , '/');
		
		
	}else{
	
		//create cookie with json string etc.
		$cookie_data = json_encode($var);
		//set cookie expires after a week
		setcookie($cookie_name, $cookie_data, time()+(3600*24*7) , '/');

	}//end if
	
}//end cookieArray 

?>

Revision: 35114
at November 2, 2010 21:04 by liamchapman


Initial Code
<?php
/**
 * Store an array inside a cookie as a JSON String
 * Useful for passing large bits of data :)
 * @author LiamC
 * @param $var = cookie value
**/
function cookieArray($var, $limit=10, $cookie_name="my_cookie")
{
	//check if we have cookie
	if($_COOKIE[$cookie_name])
	{
		
		//decode cookie string from JSON
		$cookieArr = (array) json_decode($_COOKIE[$cookie_name]);							
		
		//push additional data
		array_push($cookieArr, $var);
		
		//remove empty values
		foreach($cookieArr as $k => $v){ if($v == '' || is_null($v) || $v == 0){ unset($cookieArr[$k]); } }
		
		//encode data again for cookie
		$cookie_data = json_encode($cookieArr);
		
		//need to limit cookie size so it's no greater than 4Kb, if so reset it!
		$cookie_data = mb_strlen($cookie_data) >= 4096 ? '' : $cookie_data;
		
		//destroy cookie
		setcookie($cookie_name, '', time()-3600 , '/');
		
		//set cookie with new data and expires after a week
		setcookie($cookie_name, $cookie_data, time()+(3600*24*7) , '/');
		
		
	}else{
	
		//create cookie with json string etc.
		$cookie_data = json_encode($var);
		//set cookie expires after a week
		setcookie($cookie_name, $cookie_data, time()+(3600*24*7) , '/');

	}//end if
	
}//end cookieArray 

?>

Initial URL


Initial Description
Simple function to store an array in a cookie. Uses JSON. 

To pull data out of cookie use 'json_decode()'. It can then be looped etc.

Initial Title
Store array in cookie

Initial Tags
php, array, json

Initial Language
PHP