Store array in cookie


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.