【问题标题】:How would this argument be properly escaped in PHP?如何在 PHP 中正确转义这个参数?
【发布时间】:2024-01-07 10:12:01
【问题描述】:

我的网站有一些 PHP 生成的内容与 HTML 元素相呼应。其中一些元素响应 javascript 事件...对于一个输入元素,相关事件是 onmouseout,但我似乎无法正确转义。

$sql = mysqli_query($cxn, "SELECT stuff1, stuff2, stuff100, tags FROM myTable WHERE user_id = 'myID'");

while ($row = mysqli_fetch_assoc($sql)) {
    $Tagstring = $row['tags'];
    //lots of code

    echo "<div class='myClass1 myClass2'>
            <input type='text' name='myInput' value='".$Tagstring."' onmouseout='ajaxFunction(\"myString\", this.value.trim().replace(/,\s|\s,/g, ","))'>
          </div>";
    //more code
}

$Tagstring 是一个逗号分隔的文本子字符串。如果用户编辑他/她的标签,我试图阻止以下情况:

$Tagstring = 'tag1,tag2'; //from database table

//User edits to 'tag1, tag2';

//Pointless ajax call and access of server, since if user input = original $Tagstring, this will return false as I have set up the ajax call, but if user input !== $Tagstring, then ajax function proceeds

我对 PHP 和 Javascript 并不陌生,所以我知道 PHP 中的 str_replace 或在 "," 上分解用户输入,然后修剪分解数组的每个成员。或者,我可以使用 Javascript 在 "," 上拆分,然后在 for 循环中修剪片段(或类似的东西)。

谁能告诉我如何在我的回显函数调用中正确转义以下参数?

this.value.trim().replace(/,\s|\s,/g, ",")

【问题讨论】:

  • 对于大的echo,关闭然后重新打开PHP标签更简单。
  • $TagString$Tagstring 不同。
  • 好的...错字已修正...我的错误
  • 现在出现语法错误。你关闭字符串太早了。
  • @Blackhole....很难做到这一点,因为 div 非常大且复杂(未显示)并且会根据用户输入更改 HTML、文本和类

标签: php escaping


【解决方案1】:

我倾向于以与您的方式相反的方式回显我的输出,我觉得这更容易控制。单引号在外面,双引号在里面。

echo '<div class="myClass1 myClass2">
            <input type="text" name="myInput" value="'.$TagString.'" onmouseout="ajaxFunction("myString", this.value.trim().replace(/,\s|\s,/g, ""))">
     </div>';

您看到的错误是什么?

【讨论】:

  • 用我给你的代码试试这个&lt;input type="text" name="myInput" value="'.$TagString.'" onmouseout="ajaxFunction(''myString'', this.value.trim().replace(/,\s|\s,/g, ""))"&gt;
  • 加载资源失败:服务器响应状态为 500(内部服务器错误)...我知道这是 this.value 的替换部分,因为一旦替换被删除以产生this.value.trim(),不再是 500 –
  • 即使\"myString\" 的错误消失了,我认为这不是问题所在。由于 PHP 正在控制输出,因此客户端将其视为 html。 “myString”是变量还是什么?
  • 修复它...需要一个逗号而不是空字符串(我的错),但不管它似乎是一个逃避问题。我使用了:.replace(/,\s|\s,/g, \",\"),而 .replace(/,\s|\s,/g, ",") 和 .replace(/,\ s|\s,/g, ',') 和 .replace(/,\s|\s,/g, \',\') 导致 Uncaught SyntaxError: Unexpected token ILLEGAL 等错误
  • 奇怪,很高兴你把它修好了。
【解决方案2】:

修复它...这似乎是一个逃避问题。这有效:

onmouseout='ajaxFunction(\"AStringNotAVariable\", this.value.trim().replace(/,\s|\s,/g, \",\"))'

//.replace(/,\s|\s,/g, ",") and .replace(/,\s|\s,/g, ',') and .replace(/,\s|\s,/g, \',\') 

导致 Uncaught SyntaxError: Unexpected token ILLEGAL 等错误

【讨论】: