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中的主要内容,如果未能解决你的问题,请参考以下文章

PHP 将数组存储在cookie中

将 PHP 数组存储在单个 SQL 单元格中

用php将对象存储在数组中

您可以将函数存储在 PHP 数组中吗?

将 PHP 转换为 JavaScript。将键/值存储到数组中

将 db 值存储到 php 数组中,然后遍历数组