【问题标题】:json_encode() issue and storing in cookie issue in PHPjson_encode() 问题和存储在 PHP 中的 cookie 问题
【发布时间】:2018-10-05 20:38:33
【问题描述】:

当我转换json_encode时;它以正确的格式转换它,但是当我将它存储在 cookie 中时;格式得到改变。我想按原样存储在 cookie 中。

JSON 字符串:

{
"ID": "0",
  "basicAddress": {
    "ID": "0",
    "Line1": "327 S Main St",
    "Line2": "",
    "Line3": "",
    "City": "Fitzgerald",
    "ZipCode": "31750",
    "StateProv": "",
    "Country": "",
    "stateProv": "GA"
  },
  "Name": "",
  "Latitude": "31.7114886",
  "Longitude": "-83.25471970000001",
  "IsPreferred": "false"
}

在 COOKIE 中存储后:

%7B%22ID%22%3A%220%22%2C%22basicAddress%22%3A%7B%22ID%22%3A%220%22%2C%22Line1%22%3A%22327+S+Main+St%22%2C%22Line2%22%3A%22%22%2C%22Line3%22%3A%22%22%2C%22City%22%3A%22Fitzgerald%22%2C%22ZipCode%22%3A%2231750%22%2C%22StateProv%22%3A%22%22%2C%22Country%22%3A%22%22%2C%22stateProv%22%3A%22GA%22%7D%2C%22Name%22%3A%22%22%2C%22Latitude%22%3A%2231.7114886%22%2C%22Longitude%22%3A%22-83.25471970000001%22%2C%22IsPreferred%22%3A%22false%22%7D

【问题讨论】:

  • 请向我们展示您的代码
  • $address=json_encode($address); setcookie('地址',$address,time() +50000,"/");
  • 是的,cookie 值将被 URL 编码,这是预期的行为。澄清你在什么时候期待别的东西。
  • 您从哪里访问 cookie?使用 javascript 还是 php?
  • 您必须对它们进行编码。这就是 cookie(以及一般的 HTTP 标头)的工作方式。让 ASP 端对它们进行 urldecode(如果它没有自动完成)。

标签: php arrays json


【解决方案1】:

我找到了解决方案,它完全按照我的意愿工作

$address={
"ID": "0",
  "basicAddress": {
    "ID": "0",
    "Line1": "327 S Main St",
    "Line2": "",
    "Line3": "",
    "City": "Fitzgerald",
    "ZipCode": "31750",
    "StateProv": "",
    "Country": "",
    "stateProv": "GA"
  },
  "Name": "",
  "Latitude": "31.7114886",
  "Longitude": "-83.25471970000001",
  "IsPreferred": "false"
};
cookie_expire_time=30000;
header("Set-Cookie: address=$address; Domain=.example.com;Path=/; Max-Age=".cookie_expire_time.";");

【讨论】:

    【解决方案2】:

    setcookie 对值进行 URL 编码是正确的行为。您可以使用setrawcookie 来避免自动编码,但您需要确保自己的 cookie 格式正确以符合 HTTP。

    【讨论】:

    • 如下图所示:Array ( [type] => 2 [message] => Cookie 值不能包含以下任何 ',; \t\r\n\013\014' [file] => /opt/bitnami/apps/wordpress/htdocs/wp-content/themes/asystu/functions.php [行] => 303)
    • 好吧,你去吧……看起来你的 ASP 变体正在生成技术上无效的 cookie(尽管如此,浏览器还是不情愿地处理了这些 cookie)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2011-09-15
    • 2017-03-27
    • 2010-12-03
    相关资源
    最近更新 更多