note 119909 added to function.strip-tags

From: Date: Mon, 19 Sep 2016 06:10:00 +0000
Subject: note 119909 added to function.strip-tags
Groups: php.notes 
Request: Send a blank email to php-notes+get-206619@lists.php.net to get a copy of this message
Since strip_tags does not remove attributes and thus creates a potential XSS security hole, here is a small function I wrote to allow only specific tags with specific attributes and strip all other tags and attributes. If you only allow formatting tags such as b, i, and p, and styling attributes such as class, id and style, this will strip all javascript including event triggers in formatting tags. Note that allowing anchor tags or href attributes opens another potential security hole that this solution won't protect against. You'll need more comprehensive protection if you plan to allow links in your text. <?php function stripUnwantedTagsAndAttrs($html_str){ $xml = new DOMDocument(); //Suppress warnings: proper error handling is beyond scope of example libxml_use_internal_errors(true); //List the tags you want to allow here, NOTE you MUST allow html and body otherwise entire string will be cleared $allowed_tags = array("html", "body", "b", "br", "em", "hr", "i", "li", "ol", "p", "s", "span", "table", "tr", "td", "u", "ul"); //List the attributes you want to allow here $allowed_attrs = array ("class", "id", "style"); if (!strlen($html_str)){return false;} if ($xml->loadHTML($html_str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD)){ foreach ($xml->getElementsByTagName("*") as $tag){ if (!in_array($tag->tagName, $allowed_tags)){ $tag->parentNode->removeChild($tag); }else{ foreach ($tag->attributes as $attr){ if (!in_array($attr->nodeName, $allowed_attrs)){ $tag->removeAttribute($attr->nodeName); } } } } } return $xml->saveHTML(); } ?> ---- Server IP: 72.52.91.14 Probable Submitter: 168.1.99.252 ---- Manual Page -- http://php.net/manual/en/function.strip-tags.php Edit -- https://master.php.net/note/edit/119909 Del: integrated -- https://master.php.net/note/delete/119909/integrated Del: useless -- https://master.php.net/note/delete/119909/useless Del: bad code -- https://master.php.net/note/delete/119909/bad+code Del: spam -- https://master.php.net/note/delete/119909/spam Del: non-english -- https://master.php.net/note/delete/119909/non-english Del: in docs -- https://master.php.net/note/delete/119909/in+docs Del: other reasons-- https://master.php.net/note/delete/119909 Reject -- https://master.php.net/note/reject/119909 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#206619) next »