【问题标题】:PHP DOMDocument hasAttribute is associated to which Elements?PHP DOMDocument hasAttribute 与哪些元素相关联?
【发布时间】:2013-03-29 20:36:11
【问题描述】:

我想检查正文下的所有标签,并检查并删除它是否具有样式属性 我试过了

$user_submitted_html = "This is Some Text";
$html = '<body>' . $user_submitted_html . '</body>';

$dom = new DOMDocument();
$dom->loadHTML($html_string);
$elements = $dom->getElementsByTagName('body');
foreach($elements as $element) {

   foreach($element->childNodes as $child) {

      if($child->hasAttribute('style')) {

          $child->removeAttribute('style')

      }      
   }  
 }

如果$user_submitted_html 不仅是文本,它工作正常,意味着如果它有一些标签,但如果它只是文本,那么它会给出错误

Call to undefined method DOMText::hasAttribute()

然后我在foreach循环中得到nodeName

echo "Node Name: " . $child->nodeName

它给出了

Node Name = #text

这是什么节点名称,我已经回显了其他节点,它给出了我熟悉的div、span等。 我想知道哪些是 hasAttribute 不属于它们的元素,所以我可以在像这样使用 hasAttribute 之前设置一个条件

if($child->nodeName=="#text") {
    continue; // skip to next iteration
}
if($child->hasAttribute('style')) {
.
.
.

或任何其他解决方案???

需要更多建议。如果我只从&lt;div&gt;,&lt;span&gt;,&lt;p&gt; and &lt;a&gt; 中删除样式属性会怎样。如果其余标签可以使用样式属性,它会不会受到 xss 的影响。

【问题讨论】:

  • 这应该有助于理解节点的一般概念:stackoverflow.com/questions/4979836/…。比您更简单的方法是使用 XPath 直接查询具有 style 属性的 body 元素的 Elements 子元素,例如/html/body/*[@style]

标签: php xss domdocument


【解决方案1】:

我认为与其检查 nodeName 不如检查类 $child 是一个实例。

if ( $child instanceof DOMElement )
{
    //do your stuff
}

【讨论】:

    【解决方案2】:

    您可以使用 XPath 仅获取具有 style 属性的元素

    $xpath = new DOMXPath($dom);
    $elements = $xpath->query('//[@style]');
    
    foreach($elements as $e) {
        $e->removeAttribute('style')
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 2014-10-04
      • 1970-01-01
      • 2011-01-19
      • 2012-05-18
      • 2020-10-21
      • 1970-01-01
      相关资源
      最近更新 更多