This is a discussion on Prevent XSS using DOM Extension and/or SimpleXML within the PHP General forums, part of the PHP Programming Forums category; Hi there! Iīm building a form validator using PHP and JS. Itīs working fine by now, but I ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Hi there!
Iīm building a form validator using PHP and JS. Itīs working fine by now, but I want to make a little improvement. Here is how its working now: 1. The user fill the form. Every time he leaves the field, the JS code match the value against a regexp to validate. 2. When the user submits the form, the PHP script match all the values against the same regexp's. Now, i want to validate my fields to prevent XSS, allowing my html tags but only the attributes that I want. I thought something like: (the tags and the valid attributes). <?php $form_html_validation = array( "p"=>array(""), "a"=>array("href","name","rel"), "ol"=>array(""), "ul"=>array(""), "li"=>array(""), "h2"=>array(""), "h3"=>array(""), "h4"=>array(""), "h5"=>array(""), "h6"=>array(""), "strong"=>array(""), "em"=>array("") ); $valid_elements = "<".join("><",array_keys($form_html_validation))." >"; $userInput = strip_tags($userInput,$valid_elements); //perform DOM Attribute Validation ?> But I donīt know how to loop over every attribute for each tag in the DomTree. Someone has any ideas? Thank You |
|
|||
|
Raphael Martins wrote:
> But I donīt know how to loop over every attribute for each tag in the > DomTree. Not sure if you need to do this element by element or just want all attributes, but here are two ways using DOM. They assume $dom is an already loaded DOMDocument. 1 - Use XPath: $xPath = new DOMXPath($dom); $nodelist = $xPath->query("//@*"); foreach ($nodelist AS $attr) { print $attr->nodeName." ".$attr->nodeValue."\n"; } 2 - Walk the tree manually: function checkElement($node) { $attlist = $node->attributes; foreach ($attlist AS $attr) { print $attr->nodeName." ".$attr->nodeValue."\n"; } if ($node->hasChildNodes()) { foreach ($node->childNodes AS $child) { if ($child->nodeType == XML_ELEMENT_NODE) { checkElement($child); } } } } $root = $dom->documentElement; checkElement($root); Rob |