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.
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.