【问题标题】:Getting all tangled up in json_encode/json_parse and escaping在 json_encode/json_parse 中纠缠不清并转义
【发布时间】:2012-07-18 11:32:53
【问题描述】:

当用户在 html 表单上输入 " 或 \ 时遇到问题

输入的文本将在 html 内容和 html 属性上下文中再次显示给用户

我有以下数据流:

  1. jQuery 表单行输入
  2. $_POST
  3. 转义 html 属性:函数转义使用 html 实体或十六进制实体(" 或 \)
  4. php 中的 json_encode
  5. 一些未知的 javascript 干扰导致熔断
  6. jquery ajax 回调中的 json_parse

目标是向用户显示与输入完全相同的文本,但要正确转义以避免 xss 攻击。

现在我得到的第一件事是 $_POST 出于某种原因添加了斜杠。所以我现在首先使用stripslashes。这解决了单引号的所有问题,但如果用户输入 " 或 \ 它仍然会中断。

问题似乎是 javascript 在 json_parse 获取数据之前进行了一些解码。它将十六进制转义符转回 \ 和 " 从而杀死 json_parse。

然后我想如果在第 4 步和第 5 步之间我使用 htmlspecialchars($data, NO_QUOTES, 'utf-8') 我将 & 符号编码为 &,这应该中和 javascript 解码,但不是。它不解码 & 出于某种原因,但它确实解码 &quot 和十六进制编码......

我哪里错了? 有没有办法确切地知道 javascipt 解码并从 php 中和它?


浪费了半天,我现在在做什么:

我认为在 onsuccess 处理程序获取数据之前干扰数据可能是一些 jQuery 的事情。我现在没有时间去挖掘它并杀死它,所以我只是偷偷摸摸地通过一个 hack,这意味着 3 个字符串转换只是为了保持字符串不转换,但是嘿,开发人员的时间在这里是一种罕见的商品。

在 php 中:

    // due to a problem with the jQuery callback code which seems to decode html entities and hex entities except for &
    // we need to do something to keep our data intact, otherwise parse_json chokes on unescaped backslashes
    // and quotes. So we mask the entity by transforming the & into & here and back in js.
    // TODO: unit test this to prevent regression
    // TODO: debug the jQuery to avoid this workaround
    //
    // echo  json_encode( $response );
    echo preg_replace( '/&/u', '&', json_encode( $response ) );

在 parse_json 之前的 js 中:

    // due to a problem with the jQuery callback code which seems to decode html entities and hex entities except for &
    // we need to do something to keep our data intact, otherwise parse_json chokes on unescaped backslashes
    // and quotes. So we mask the entity by transforming the & into & here and back in js.
    // See function xxxxxx() in file xxxxx.php for the corresponding transformation
    //
    responseText = responseText.replace( /&/g, '&' );

目前我懒得为其编写单元测试,但我似乎无法破解它。

真正的问题仍然是如何在获得相同结果的同时消除不需要的转换?

【问题讨论】:

  • 在将用户输入发送到 PHP 之前,您能否在用户输入上尝试 w3schools.com/jsref/jsref_escape.asp
  • @user868766 — 该功能已弃用。它不应该被使用。
  • “我哪里出错了?” ——你已经走了六步。依次浏览每一个,看看数据在哪里停止按您期望的方式格式化。
  • 您不应该在将数据放入 JSON 之前对 HTML 进行编码。您应该在将数据放入 HTML 之前对 HTML 进行编码。
  • @Quentin:谢谢,我不知道。

标签: php javascript jquery json escaping


【解决方案1】:

尝试在 php.ini 中关闭“Magic Quotes”。这样,数据通过 $_POST 进入,就像用户键入它一样。见:http://www.php.net/manual/en/security.magicquotes.disabling.php

那你就可以根据自己的需要转义了。

【讨论】:

  • 好吧,感谢您的提示,但根据 phpinfo(),magic_quotes_gpc 已关闭。除此之外,这并不能解决 javascript 的麻烦。
  • 我也花了半天时间与 JSON 中出现的反斜杠作斗争,最终出现在这里。非常感谢@alexwells,它对我有用。
【解决方案2】:

我遇到了类似您的问题并使用了 utf8_encode() 函数。现在它运作良好。可以试试吗?

【讨论】:

  • 似乎没有任何改变。无论如何,我的数据已经是 utf-8,我不喜欢使用随机函数来处理它们不适合的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
相关资源
最近更新 更多