Ok, so I had an odd requirement on a recent project. In order to get around limitations of our CMS and caching I needed to store and update a JSON object in a cookie after making several AJAX calls. Later if a user completed a process the information stored in this cookie is used to identify choices made earlier. The completion can span a few minutes to several weeks, ie. page conversion with virtually no time restriction.
When I went to extract the encoded JSON string from the $_COOKIE global I started getting JSON Syntax errors (actually the bugs cropped up before that point but that is when I started to figure out what was happening). I was using the built-in JSON.stringify in Javascript to set the cookie value, and json_decode in PHP.
Apparently, PHP will escape the quotes in a string value coming out of $_COOKIE, this caused the JSON syntax error, and the cascade effect after. I did not see any mention in the PHP JSON functions or $_COOKIE docs. I ended up doing a preg_replace on the ‘\’ and removing them, and it ‘works’ now.
That seems to be like a hacky work around. Was/is there something I am missing? Is there a better way to do this in the future?
when echoing the values and json_last_error():
$cookie = $_COOKIE[‘cookie_name’]; => {\”suffix\”:\”general\”…}
$cookie = json_decode($cookie, true); => Syntax Error: NULL
$cookie = preg_replace(‘/\\/’, “”, $cookie); => {“suffix”:”general”…}
$cookie = json_decode($cookie, true); => No Errors: ARRAY
you need to add the second parameter of json_encode as (some constants need PHP 5.3)
also, you’ll need
json_decode(stripslashes($json))since it seemsmagic_quotes_gpcis on