cookie_encode & cookie_decode


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

This is a great way to save complex objects as cookie values. You can't just json_encode because commas are not legal in cookie values. Remember not to use this for anything too big because cookies have a 4KB limit.


Copy this code and paste it in your HTML
  1. /**
  2.  * Author: Andrew Hedges, [email protected]
  3.  * License: free to use, alter, and redistribute without attribution
  4.  */
  5.  
  6. /**
  7.  * Turn any object (e.g., an array) into a string you can save in a cookie
  8.  * @param object $obj
  9.  * @return string
  10.  */
  11. function cookie_encode($obj) {
  12. $value = json_encode($obj);
  13. $value = base64_encode($value);
  14. return $value;
  15. }
  16.  
  17. /**
  18.  * Turn a string encoded by cookie_encode back into an object
  19.  * @param string $value
  20.  * @return object
  21.  */
  22. function cookie_decode($value) {
  23. $value = base64_decode($value);
  24. $value = json_decode($value, true);
  25. return $value;
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.