Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store raw json string in cookie with PHP?

Tags:

json

arrays

php

I am trying to store a json string in a cookie, however, the special characters, such as; {"":""} get encoded.

I have tried setrawcookie(), but it doesn't store more than one property-value.

$array = array('test' => 'value', 'anothertest' => 'not stored');

setrawcookie($this->cookie_customs_name, stripslashes(json_encode($array)), 
    strtotime($this->cookie_life_time), $this->cookie_path, $this->cookie_domain);

What am I doing wrong here?

Also, is it possible to achieve this using the setcookie() method?

like image 856
Taner Avatar asked Oct 12 '25 10:10

Taner


1 Answers

The special characters should be escaped automatically when you use setcookie(). You should just need to remove the slashes once you retrieve the cookie.

$array = array(....);

setcookie($this->cookie_customs_name, json_encode($array), ...);

When retrieving the cookie:

$cookie = stripslashes($_COOKIE[$this->cookie_customs_name]);
$cookie = json_decode($cookie);

Untested, but should be all that is needed.

like image 199
Chris Avatar answered Oct 14 '25 07:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!