【问题标题】:how to store raw json string in cookie with PHP?如何使用 PHP 将原始 json 字符串存储在 cookie 中?
【发布时间】:2015-09-14 14:45:11
【问题描述】:

我正在尝试将 json 字符串存储在 cookie 中,但是,特殊字符,例如; {"":""} 被编码。

我试过setrawcookie(),但它不会存储多个属性值。

$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);

我在这里做错了什么?

另外,是否可以使用setcookie() 方法来实现这一点?

【问题讨论】:

  • 那么,有什么问题呢?被编码的字符有什么问题?不能在需要阅读的时候直接解码吗?
  • 您应该在设置时删除您的 stripslashes() 调用。您需要转义这些字符。只需在检索 cookie 时删除它们即可。
  • stripslashes() on json 可能会损坏 json 字符串。不要那样做。

标签: php arrays json


【解决方案1】:

当您使用setcookie() 时,应自动转义特殊字符。检索 cookie 后,您应该只需要删除斜杠。

$array = array(....);

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

检索 cookie 时:

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

未经测试,但应该是所有需要的。

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 2013-10-10
    • 2012-01-19
    相关资源
    最近更新 更多