php从完整$ content Body和 /或head,inline,inline,index等中删除脚本标签



这个主题不会让我要求它是身体的解决方案内联,索引等。

从HTML内容中删除脚本标签

我想控制我删除的脚本以及多少脚本。

我希望我不必经历有关使用某些某些的论点除了正直之外,其他事情再次。我最喜欢这个主题的答案是从Binh出发的:

$html = preg_replace("/<script.*?/script>/s", "", $html) ? : $html;

我希望通过尽可能多的粒度控制方法进行这种方法,但这可以删除整个$content中的脚本。我想看到这一点是为了从身体中删除脚本,或从身体上到底部的身体)。

也只是从头部上删除脚本(或远至远端的身体)。也由索引。像身体的第1,头部第四等。

最后,我想看到内联元素js删除,并具有尽可能多的控制尽可能。

谢谢

我最终会回答您的问题,让我对您要做什么的解释

您尚未说过,我不太确定您为什么要这样做。从用户收集原始的HTML然后在其他地方显示它被认为是一个巨大的安全漏洞。摆脱所有javaScript,纯粹是使用正则义务很难。删除脚本标签很容易,但是删除内联JavaScript将是困难的部分。虽然可能会,但我将建议找到另一种执行您的任务的方法,而不是给用户一个网页的JavaScript划分版本。

一种方法是通过iframe。使用

<iframe src="html_you_want_to_strip" sandbox=""></iframe> 

将禁用所有JavaScript从iFrame内部运行。请记住,在不使用JavaScript的情况下,还有其他方法可以将恶意物品加载到您的网站中。

现在,我已经解释了您在剥离JavaScript方面应该做什么,以回答您的问题,

a。仅从身体或标题中删除脚本标签:

删除JavaScript时获得粒度的最佳方法是使用PHP的Domdocument类。基本上,您将将文档加载到此Domdocument类中,并将其剥离您想要的任何脚本标签。例如,如果您只想摆脱体内的脚本标签,则可以写下类似的内容:

<?php
$html = "the HTML you want filtered";
$DOM = new DOMDocument('1.0','utf-8');
$DOM->loadHTML($html);
$bodyTags = $DOM->getElementsByTagName('body');
/* 
 We will run under the assumption that the user has the ability to add two 
 body tags and hide information in the second one, that is why we don't 
 just use $DOM->getElementsByTagName('body')[0] 
*/
foreach($bodyTags as $body){
    foreach($body->getElementsByTagName('script') as $script){
        $script->parentNode->removeChild($script);
        /*
         The reason we have to this is because you cant just do 
         $script->remove(), that would be too easy :)
        */
    }
}

上面的相同代码可用于从Head标签中剥离脚本。如果您想删除具有一定索引的项目,则可以使用foreach

进行以下操作
$i=0;
foreach($body->getElementsByTagName('script') as $script){
    if($i!==(INDEX_TO_KEEP)){
        $script->parentNode->removeChild($script);
    }
}

b。删除内联JavaScript

我们可以使用相同的DomDocument Parser,除了这次在所有元素上解析外,寻找所有JavaScript事件(值得庆幸的是,所有元素都以ON开头)。代码将如下。

<?php
//starting where the last code leaves off
foreach($DOM->getElementsByTagName('*') as $element){
    //This selects all elements
    foreach($element->attributes as $attribute){
        if(preg_match('/on.*/',$attribute)==1){
            /*
             "on" looks for on and ".*" states that there 
             can be anything after the on (onmousemove,onload,etc.)
            */
            $element->removeAttribute($attribute)
        }
    }
}

在您的代码末尾,您需要保存剥离的HTML并将其退还给用户

$parsedHTML = $DOM->saveHTML()

相关内容

最新更新