【发布时间】:2012-07-18 11:32:53
【问题描述】:
当用户在 html 表单上输入 " 或 \ 时遇到问题
输入的文本将在 html 内容和 html 属性上下文中再次显示给用户
我有以下数据流:
- jQuery 表单行输入
- $_POST
- 转义 html 属性:函数转义使用 html 实体或十六进制实体(
"或\) - php 中的 json_encode
- 一些未知的 javascript 干扰导致熔断
- jquery ajax 回调中的 json_parse
目标是向用户显示与输入完全相同的文本,但要正确转义以避免 xss 攻击。
现在我得到的第一件事是 $_POST 出于某种原因添加了斜杠。所以我现在首先使用stripslashes。这解决了单引号的所有问题,但如果用户输入 " 或 \ 它仍然会中断。
问题似乎是 javascript 在 json_parse 获取数据之前进行了一些解码。它将十六进制转义符转回 \ 和 " 从而杀死 json_parse。
然后我想如果在第 4 步和第 5 步之间我使用 htmlspecialchars($data, NO_QUOTES, 'utf-8') 我将 & 符号编码为 &,这应该中和 javascript 解码,但不是。它不解码 & 出于某种原因,但它确实解码 " 和十六进制编码......
我哪里错了? 有没有办法确切地知道 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