如何输出HTML但如何防止XSS攻击 [英] How to output HTML but prevent XSS attacks
问题描述
我写了一个php脚本来获取电子邮件内容.
I wrote a php script to fetch the email content.
这些内容是HTML格式.
These contents are HTML format.
我想显示以下内容
<?php
$email_content = '
<html>
<script>alert("XSS");</script>
<body>
<div>Line1</div>
<div>Line2</div>
</body>
</html>
';
echo $email_content;
?>
如您所见,它将引起XSS攻击.但是,如果我使用htmlspecialchars函数,它将无法显示正确的HTML格式,在这种情况下该怎么办?谢谢.
As you can see, it will cause XSS attacks. But if I use htmlspecialchars function, it will not show the correct HTML format, how should I do in this case? Thanks.
推荐答案
HTMLPurifer 可以做到:
require_once '/path/to/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);
它需要脏HTML(即可能包含Javascript)并删除任何脚本.
It takes dirty HTML (ie possibly containing Javascript) and removes any script.
PHP没有任何本地或内置的东西可以删除Javacript,例如HTMLPurifier.您可以使用DOMDocument,但这将是一个漫长的任务,因为Javascript可以在某些属性(错误,onclick)中执行,而不仅限于<script></script>
.
PHP doesn't have anything native or built in that can remove Javacript like HTMLPurifier. You could use DOMDocument but this would be a lengthy task because Javascript can execute in some attributes (onerror, onclick) and is not just limited to <script></script>
.
这篇关于如何输出HTML但如何防止XSS攻击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!