PHP function for tagging, except for the list of white tags and attributes

I need to remove all HTML tags and attributes from user input, except those that are considered "safe" (i.e. whitelist approach).

strip_tags () separates all tags except those listed in the parameter $allowable_tags. But I also need to be able to erase all attributes that are not included in the white list; for example, I want to allow a tag <b>, but I do not want to allow an attribute onclickfor obvious reasons.

Is there a function to do this, or will I have to make my own?

+3
source share
2 answers

, strip_tags - , DOMDocument,

$string = strip_tags($string,'<b>');
$dom = new DOMDocument();
$dom->loadHTML($string);
$allowed_attributes = array('id');
foreach($dom->getElementsByTagName('*') as $node){
    for($i = $node->attributes->length -1; $i >= 0; $i--){
        $attribute = $node->attributes->item($i);
        if(!in_array($attribute->name,$allowed_attributes)) $node->removeAttributeNode($attribute);
    }
}
var_dump($dom->saveHTML());
+13

, , , . , .

-1

Source: https://habr.com/ru/post/1757644/


All Articles