본문으로 바로가기

Cookie Array Function

category Backend/PHP 2020. 3. 12. 18:09
<?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 
 
?>

'Backend > PHP' 카테고리의 다른 글

html 태그 제거 정규식  (0) 2020.05.07
post_max_size & upload_max_filesize  (0) 2020.04.22
인증번호 6자리 (숫자)  (0) 2020.01.17
csv 대용량 파일 인코딩 후 다운로드까지  (0) 2019.11.29
ftp 사용법  (0) 2019.11.26