PHP 将数组存储在cookie中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 将数组存储在cookie中相关的知识,希望对你有一定的参考价值。

<?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 

?>

以上是关于PHP 将数组存储在cookie中的主要内容,如果未能解决你的问题,请参考以下文章

在cookie中存储数组

如何将php的cookie转化成对象或数组

PHP 会话与 Cookies [重复]

PHP Cookie

如何从 php 中的 cookie 将数据保存在 mysql 中? [复制]

在 php 中更新 cookie 值