I needed to use a cookie to store a hash string so a user would be remembered the next time they come to visit a site. I was required to store their user id (numeric) and also a secret string that gets hashed. This typically would have required two cookies but I didn’t want two cookies. So I did what any one would do: use json to store my data inside of a cookie.
Little do you know, you can set cookies as arrays but it still causes multiple cookies to be made and sent back and forth between the server and the client. So wrapping my id and hash together in a single cookie saves me time and also saves the user some bandwidth, the bandwidth of only one cookie versus two.
So how did I accomplish putting a json string inside of a cookie? I used PHP5′s json_encode function and of course setcookie . The code is short and simple:
[php]
$toCookie = array(“id” => 1, “hash”=>”6b585b736c476e772ee8586957c501254a04917b”);
$json = json_encode($toCookie);
setcookie(“json_cookie”, $json);
[/php]
That was the easy part. Now, how about getting the delicious little guys out? That’s sort of easy, but first, do you know your old friend, get_magic_quotes_gpc , well, if you haven’t met, do it now, because we need his help. A lot of servers have magic quotes turned on, I even had this problem with xampp by default. You have to account for that or your cookie will not be decoded in one piece .
[php]
if (get_magic_quotes_gpc() == true) {
foreach($_COOKIE as $key => $value) {
$_COOKIE[$key] = stripslashes($value);
}
}
[/php]
So now that you’ve cleaned the slashes up, getting the data is easy. Just run json_decode on the cookie. You can decide if you want an object or an array out by passing true as a second argument to get an array.
[php]
$cookie = json_decode($_COOKIE["json_cookie"], true);
var_dump($cookie);
[/php]
Again, it’s not hard and it really does save you from the cookie array syntax mess and also saves the user of having extra cookies.
I hope this helps you to be wise when using cookies.