纠结于json_encode/json_parse并逃脱

Getting all tangled up in json_encode/json_parse and escaping

本文关键字:json parse 逃脱 encode      更新时间:2023-11-17

当用户在 html 表单上输入 " 或 '' 时出现问题

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

我有以下数据流:

  1. j查询表单行输入
  2. $_POST
  3. HTML
  4. 属性的转义:函数使用 HTML 实体或十六进制实体("\ (进行转义
  5. json_encode 在 PHP 中
  6. 一些未知的 JavaScript 干扰会熔断保险丝
  7. json_parse 在 jquery ajax 回调中

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

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

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

所以后来我想,如果在步骤 4 和 5 之间我使用 htmlspecialchars( $data,NO_QUOTES,'utf-8' ( 我将 & 符号编码为 & ,这应该中和 javascript 解码,但没有。由于某种原因,它不会解码&,而它确实解码了"和十六进制编码......

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


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

我认为在 onsuccess 处理程序获得数据之前干扰数据可能是一些 jQuery 的事情。我现在没有时间挖掘它并杀死它,所以我只是用一个黑客偷偷溜过去,这意味着 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中关闭"魔术行情"。这样,数据就会通过 _POST 美元进入,就像用户键入数据一样。请参阅:http://www.php.net/manual/en/security.magicquotes.disabling.php

然后你可以根据需要转义它。

我遇到了像你的问题一样的问题,并使用了utf8_encode((函数。现在它运行良好。你能试试吗?