从字符串中删除任何事件 JavaScript


delete any event javascript from a string

Is there an easy way to remove with php php字符串中的任何类型的事件HTML。例如,对于事件提交,鼠标输出,鼠标悬停,单击,模糊,焦点等,以防止javascript注入,对于以下情况:有没有一种简单的方法可以用 php 删除 php srtring 中的任何类型的事件 HTML。例如,对于事件提交,鼠标输出,鼠标悬停,单击,模糊,焦点等,以防止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:I无法转义所有文本或删除所有标签,因为如果我想在 html 中显示某些部分。Imagine you want to show a user creates html to another and want to avoid the injection of javascript

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

一个处理这个问题的好库是 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>