Strip tags... removing attributes from tags...

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Strip tags... removing attributes from tags...

Post by Mr Tech »

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...

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);
?>
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?
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

Did a bit of searching and finally found something that worked!

http://www.phpclasses.org/browse/file/8941.html
matthijs
DevNet Master
Posts: 3360
Joined: Thu Oct 06, 2005 3:57 pm

Post by matthijs »

You could also replace the word 'forbidden' in the preg_replace with an empty string ''.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

http://code.tatzu.net/cleantags/ could also be of interest.
Post Reply