Does anyone know of a good function out there for filtering generic input from forms? Zend_Filter_input seems to require prior knowledge of the contents of the input and I\'
All above methods don't allow to preserve some tags like <a>
, <table>
etc. There is an ultimate solution http://sourceforge.net/projects/kses/
Drupal uses it
According to www.mcafeesecure.com General Solution for vulnerable to cross-site scripting (XSS) filter function can be:
function xss_cleaner($input_str) {
$return_str = str_replace( array('<','>',"'",'"',')','('), array('<','>',''','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
I have a similar problem. I need users to submit html content to a profile page with a great WYSIWYG editor (Redactorjs!), i wrote the following function to clean the submitted html:
<?php function filterxss($str) {
//Initialize DOM:
$dom = new DOMDocument();
//Load content and add UTF8 hint:
$dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">'.$str);
//Array holds allowed attributes and validation rules:
$check = array('src'=>'#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i','href'=>'|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i');
//Loop all elements:
foreach($dom->getElementsByTagName('*') as $node){
for($i = $node->attributes->length -1; $i >= 0; $i--){
//Get the attribute:
$attribute = $node->attributes->item($i);
//Check if attribute is allowed:
if( in_array($attribute->name,array_keys($check))) {
//Validate by regex:
if(!preg_match($check[$attribute->name],$attribute->value)) {
//No match? Remove the attribute
$node->removeAttributeNode($attribute);
}
}else{
//Not allowed? Remove the attribute:
$node->removeAttributeNode($attribute);
}
}
}
var_dump($dom->saveHTML()); } ?>
The $check array holds all the allowed attributes and validation rules. Maybe this is useful for some of you. I haven't tested is yet, so tips are welcome
the best and the secure way is to use HTML Purifier. Follow this link for some hints on using it with Zend Framework.
HTML Purifier with Zend Framework
htmlspecialchars()
is perfectly adequate for filtering user input that is displayed in html forms.
Try using for Clean XSS
xss_clean($data): "><script>alert(String.fromCharCode(74,111,104,116,111,32,82,111,98,98,105,101))</script>