htmlentities 允许 <a> 链接 - 如何?

htmlentities to allow <a> links - How?

为了确保我的输入安全,我在 php:

中使用了 htmlentities
$input = $_POST['field'];
$result = htmlspecialchars($input);

这行得通,但后来我意识到,在某些输入中,我需要允许一些基本标记,如 <b><i>、版权徽标和用户的基本内容。所以我开始这样做:

$result = $_POST['ftext'];
$presanitize = htmlspecialchars($result);
$newftext = str_replace(array("&lt;i&gt;", "&lt;b&gt;", "&lt;/i&gt;", "&lt;/b&gt;", "&copy;", "&quot;", "&lt;a&gt;", "&lt;&#47;a&gt;"), 
array("<i>", "<b>", "</i>", "</b>", "©", '"', "<a>", "</a>"), $presanitize); 

现在我们来谈谈我的主要问题:如何允许像 <a><img> 这样的东西,我们没有标签并且不知道里面有什么?

我可以替换 ,因为它总是只有 ,但如果我替换 ,它就不会工作,因为里面会有很多东西 (<a href="http://link.com">Text</a>)。 我应该怎么办?提前致谢。

简单的回答是:你不知道。这就是为什么许多流行的论坛系统使用某种不仅仅是普通 HTML 的标记的部分原因。否则人们可以并且会以某种方式做令人讨厌的事情。

<img src="http://example.com/random-pic.jpg" onload="location.href='http://some.nasty.page/exploit';"/>

但是您可以删除事件标签吗?当然可以,但是您会及时了解浏览器支持的所有内容及其怪癖吗?你真的能比所有人都聪明吗?

如果您仍想这样做,请寻找提供此功能的文档齐全、经过测试和使用的库或脚本。 PHP essentially has this built in, but it's really barebone. Some keywords to look for would be "php html sanitizer" 或类似的。

我个人建议您只支持 Markdown 或类似 BBCode 的语法(再次强调:有许多现成可用的代码片段和库)。除非万不得已,否则不要重新发明轮子。

<a><img> 标签使用 preg_replace():

$new = preg_replace('/&lt;(img|a)(.*?)&gt;/i', '<>', $input);

请注意,这完全未经测试,但应该会给您提示如何解决您的问题。