Strip tags... removing attributes from tags...
Posted: Sun Mar 18, 2007 10:06 pm
I want to be able to strip certain tags and attributes from code so that users cannot add dangerous code. I found what looked like a good PHP 5 script that did the trick however I need it in PHP 4...
I had a look through the PHP.net code samples and found one that almost suited me...
It seems to work however instead of removing the attributes, it replaces them with forbidden which isn't very good markup...
Does anyone know of maybe a better script or of a way to make this script remove attributes completely?
I had a look through the PHP.net code samples and found one that almost suited me...
Code: Select all
<?php
/**
* Allow these tags
*/
$allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img>';
/**
* Disallow these attributes/prefix within a tag
*/
$stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|'.
'onmousemove|onmouseout|onkeypress|onkeydown|onkeyup;
/**
* @return string
* @param string
* @desc Strip forbidden tags and delegate tag-source check to removeEvilAttributes()
*/
function removeEvilTags($source)
{
global $allowedTags;
$source = strip_tags($source, $allowedTags);
return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);
}
/**
* @return string
* @param string
* @desc Strip forbidden attributes from a tag
*/
function removeEvilAttributes($tagSource)
{
global $stripAttrib;
return stripslashes(preg_replace("/$stripAttrib/i", 'forbidden', $tagSource));
}
// Will output: <a href="forbiddenalert(1);" target="_blank" forbidden =" alert(1)">test</a>
echo removeEvilTags($bigstr);
?>Does anyone know of maybe a better script or of a way to make this script remove attributes completely?