在cookie中存储数组

Posted

tags:

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

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.
  1. <?php
  2. /**
  3.  * Store an array inside a cookie as a JSON String
  4.  * Useful for passing large bits of data :)
  5.  * @author LiamC
  6.  * @param $var = cookie value
  7.  * @param $limit = size limit. default and max size for a cookie is 4kb.
  8. **/
  9. function cookieArray($var, $limit=4096, $cookie_name="my_cookie")
  10. {
  11. //check if we have cookie
  12. if($_COOKIE[$cookie_name])
  13. {
  14.  
  15. //decode cookie string from JSON
  16. $cookieArr = (array) json_decode($_COOKIE[$cookie_name]);
  17.  
  18. //push additional data
  19. array_push($cookieArr, $var);
  20.  
  21. //remove empty values
  22. foreach($cookieArr as $k => $v){ if($v == '' || is_null($v) || $v == 0){ unset($cookieArr[$k]); } }
  23.  
  24. //encode data again for cookie
  25. $cookie_data = json_encode($cookieArr);
  26.  
  27. //need to limit cookie size. Default is set to 4Kb. If it is greater than limit. it then gets reset.
  28. $cookie_data = mb_strlen($cookie_data) >= $limit ? '' : $cookie_data;
  29.  
  30. //destroy cookie
  31. setcookie($cookie_name, '', time()-3600 , '/');
  32.  
  33. //set cookie with new data and expires after a week
  34. setcookie($cookie_name, $cookie_data, time()+(3600*24*7) , '/');
  35.  
  36.  
  37. }else{
  38.  
  39. //create cookie with json string etc.
  40. $cookie_data = json_encode($var);
  41. //set cookie expires after a week
  42. setcookie($cookie_name, $cookie_data, time()+(3600*24*7) , '/');
  43.  
  44. }//end if
  45.  
  46. }//end cookieArray
  47.  
  48. ?>

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

PHP 将数组存储在cookie中

在cookie中存储数组

如何在 laravel 5.4 中存储数组 cookie?

js代码片段: utils/lcoalStorage/cookie

存储在 $_SESSION 但显示在 $_COOKIES 数组中的值

我想将 Javascript 数组存储为 Cookie