gpt4 book ai didi

php - 在没有 XSS 注入(inject)的情况下保留 HTML 代码?

转载 作者:行者123 更新时间:2023-12-04 17:54:25 25 4
gpt4 key购买 nike

我收到消息说我的用户在文本区域中写入并以这种格式保存在数据库中:

nl2br(htmlentities($_POST['message']))

有了它我可以转换 /n /t<br/>保留换行符。

假设我的用户写了以下消息:

Hello World

* One
* Two

<script>alert('hello')</script>

此代码将保存在我的数据库中,但是当我选择此值并显示它时,该脚本将执行 javascript alert .

如何在没有任何 XSS 问题的情况下显示该消息?并保留换行符?

最佳答案

考虑使用 strip_tags在存储之前在消息上:

// strip out tags
$store_me = strip_tags($_POST["message"]);
// this is your previous technique
$store_me = nl2br(htmlentities($store_me));

补充一点,你应该考虑添加一个Cross-Site Request Forgery (CSRF) token 到您的表单。即,将随机生成的 token 存储在 session (或 cookie)中,并将此 token 作为隐藏输入显示在您的表单中,以便它与数据一起提交。

然后,在处理 POST 操作的页面中,确保 CSRF token 的 POSTed 值与 session (或 cookie)中的匹配。

有一篇关于防止 CSRF 的 SO 帖子 here .

编辑:为了回应您的额外评论,这里有更多信息。

您也可以使用此函数删除整个脚本,但它不会捕获每个脚本。例如,如果脚本包含“<”字符。

$str = "
Hello World

* One
* Two

<script>alert('hello')</script>
a whole bunch of data here
blah blah

and OH MY another script
<script type=\"text/javascript\">
alert('hello');
</script>


<script type=\"text/javascript\">
var sneaky = \"<\";
alert('hello');
</script>
";


function remove_script_tags($str) {
return preg_replace('#<[^>]*script[^>]*>[^<]+</[^>]*script[^>]*>#sm', '', $str);
}

echo remove_script_tags($str) . "\n";

您可以使用此功能来检测脚本,这些脚本在检测脚本尝试方面应该非常有效,但也可能检测善意的帖子就像您现在正在阅读的这篇帖子。

function contains_script_tag($str) {
return preg_match('#<[^>]*script[^>]*>#sm', $str);
}

这两个脚本也可能会捕捉到一个很长但无害的帖子,如下所示:

here is a harmless line 2 < 3
this line casually mentions "script"
oh and another harmless line 4 > 3

关于php - 在没有 XSS 注入(inject)的情况下保留 HTML 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41640160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com