如何转义脚本标签?

问题描述 投票:0回答:1

这是我的代码:

    // to make tags stable, wrap them into <html> tag
    $post_content_html = "<html>".$html."</html>";

    $dom = new DOMDocument;
    libxml_use_internal_errors(true);
    $dom->loadHTML(mb_convert_encoding($post_content_html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query('//@*');
    foreach ($nodes as $node) {
        if($node->nodeName != "src" && $node->nodeName != "href" && $node->nodeName != "alt") {
            $node->parentNode->removeAttribute($node->nodeName);
        }
    }

    $post_content_html = $dom->saveHTML($dom->documentElement);

    // To strip <html> tag which been wrapped
    $post_content_html = preg_replace('/^<html>/', '', $post_content_html);
    $post_content_html = preg_replace('/<\/html>$/', '', $post_content_html);

如您所见,我的代码删除了srchrefalt属性。但是,我的客户端仍然无法抵御XSS攻击,因为用户也可以注入<script>标记(包括内部的一些js代码),任何想法我该如何转义script标记?

php
1个回答
0
投票

尽管清理HTML的任务看起来很简单,但事实并非如此。您不能可靠地exclude HTML的某些部分并获得安全的东西。注入不安全内容的方法有很多(我是说这),您甚至不会想到其中的大多数。

唯一或多或少安全的方法是维护HTML标签和属性的白名单,并过滤属性的内容。但是由于这是一项艰巨的任务,所以也许您最好的选择是使用http://htmlpurifier.org/

甚至更好-不允许任何HTML。例如,如果这是一个选项,请使用Markdown。

© www.soinside.com 2019 - 2024. All rights reserved.