How to store large JSON String in cookie ? I have to use cookie only, session is not an option in my case. Can anyone post example code to compress string and store in cookie and also retrieve that successfully. Thanks.
-
Did you read php.net/manual/en/features.cookies.php?Jon– Jon2012-03-27 11:30:16 +00:00Commented Mar 27, 2012 at 11:30
-
Have a look at stackoverflow.com/questions/4225030/…Naveed– Naveed2012-03-27 11:32:39 +00:00Commented Mar 27, 2012 at 11:32
-
@NAVEED: No issue to store small json string in cookie.Riz– Riz2012-03-27 11:35:25 +00:00Commented Mar 27, 2012 at 11:35
3 Answers
Compressing the data doesn't seem like such a great idea. Rather, I'd keep it in a database and only store the database entry's ID in a cookie. That would also prevent people from tampering with the data, albeit tampering with the ID will still be possible. Using sessions would be better and eliminate this.
However, if you insist on storing the data in a cookie, you can compress the data using either gzcompress(), gzdeflate() or gzencode(). These all offer compression. gzdeflate() would be the best choice for your problem, seeing that it is most space-efficient.
$compressedJSON = gzdeflate($json, 9);
setcookie('json', $compressedJSON);
And to read it
$compressedJSON = $_COOKIE['json'];
$json = gzinflate($compressedJSON);
Keep in mind that even if the compression will be enough for your data to stay within the 4K limit, you might eventually exceed that, should the amount of JSON data you need stored grow.
I still suggest you use a database instead.
2 Comments
If your information is that large, you may want to look into using local storage instead. Not all browsers support local storage, but all modern ones do. If your cookie is too large, you run the risk of getting 431 http error.
So you don't have size issues, and don't have to pass a large cookie with every request, you should just store a unique ID in the cookie. Then you can retrieve the large data object from memcache, mysql, or any other server side storage using the unique ID. No sessions required.
2 Comments
Something like this?
Encode
$sJSON = json_encode($sSomeJSONData);
setcookie('json', $sJSON);
Decode
$sJSON = json_decode($_COOKIE['json']);
--- EDIT ----
Go with Kristian's answer for using gzip or a database it makes the most sense... BUT if you can't use a database you could build the session manually.
All a session is, technically, is a text file stored outside the web-tree containing data. You could duplicate that process using something like uniqid() to generate a "session name".
Create a text file, in a given directory, using that "session name" as the file name and store the "session name" in your cookie.
Then simply use serialize(), unserialize() and file_put_contents(), file_get_contents() to transfer your data between your program and your text file, using the data in the cookie to find the text file.
It would need some sanity checks and hijacking prevention but the principle is sound.