0

Is there an easy way to remove with php php 字符串中的任何类型的事件 HTML。例如事件 提交、mouseOut、mouseOver、单击、模糊、聚焦等。为了防止 javascript 注入,对于以下情况:是否有一种简单的方法可以使用 php删除 php srtring 中的任何类型的事件 HTML。例如事件 提交、mouseOut、mouseOver、单击、模糊、聚焦等。为了防止 javascript 注入,对于以下情况:

$text= 'mi secure html <div id="javascript_injection" onfocus=function(){SomeJavaScriptCode}></div> <p> Im interested in showing the resulting html </p>'

echo $text = 'mi secure html <div id="javascript_injection" > example </div> <b> Im interested in showing the resulting html </b>

我也有兴趣展示这个:

'mi secure html <div id="javascript_injection" > example </div> <b> Im interested in showing the resulting html </b>

PD:我无法转义所有文本或删除所有标签,因为如果我想在 html 中显示某些部分。Imagine you want to show a user creates html to another and want to avoid the injection of javascript

4

1 回答 1

4

解决此类问题的最佳方法是通过白名单而不是黑名单。这个想法是你定义你允许的标签/属性,而不是试图过滤掉不好的东西。

处理这个问题的一个很好的库是http://htmlpurifier.org/。您可以对其进行自定义以使其允许您想要保留的内容。

require_once '/path/to/HTMLPurifier.auto.php';

$dirty_html = '<a href="test.html" onclick="alert()">Test</a>'

$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

echo $clean_html

输出:

<a href="test.html">Test</a>
于 2013-01-22T12:48:43.313 回答