如何输出HTML,但防止XSS攻击


How to output HTML but prevent XSS attacks

我编写了一个php脚本来获取电子邮件内容。

这些内容是HTML格式。

我想显示内容,如下所示

<?php 
$email_content = '
    <html>
        <script>alert("XSS");</script>
        <body>
            <div>Line1</div>
            <div>Line2</div>
        </body>
    </html>
';
echo $email_content;
?>
如您所见,它将导致XSS攻击。但是如果我使用htmlspecialchars函数,它不会显示正确的HTML格式,在这种情况下我该怎么办?谢谢。

HTMLPurifer可以这样做:

require_once '/path/to/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

它接受脏HTML(即可能包含Javascript)并删除所有脚本。

PHP没有任何原生或内置的东西可以像HTMLPurifier那样删除javascript。您可以使用DOMDocument,但这将是一个冗长的任务,因为Javascript可以在某些属性(onerror, onclick)中执行,而不仅仅局限于<script></script>

您应该使用strip_tags()函数,并且只允许您希望用户添加的标签。

echo strip_tags($text, '<p><a>');

这一行允许<p><a>标签,其他标签将被删除。

htmlspecialchars()的工作方式完全不同。

从手册:

执行的翻译为:

 '&' (ampersand) becomes '&amp;'
 '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
 "'" (single quote) becomes '&#039;' (or &apos;) only when ENT_QUOTES is set.
 '<' (less than) becomes '&lt;'
 '>' (greater than) becomes '&gt;'

有一篇很好的关于XSS预防和CSRF预防的文章,请阅读。