RSS Feed

Detect if user input contains prohibited tags

Inspired by my previous article on XSS I thought I’d show a quick, simple and nice way to detect if user input contains some form of script or prohibited tags.

Thankfully PHP developers have a function known as strip_tags. This function strips any tags. Anything contained within the “<” (less than) and “>” (greater than) brackets are stripped from the provided string.

strip_tags(); accepts a second parameter, a list of allowed tags – this is extremely useful if you do not wish to prohibit all tags. Simply provide the list of allowed tags in a string like the example below shows.

$allowed_tags = '&lt;strong&gt;&lt;b&gt;';
if(strlen($value) != strlen(strip_tags($value, $allowed_tags))
  // Throw error

Let’s break the script down. Firstly we are defining a list of allowed tags, in this case we’re allowing bold tags only.

Next we do a length comparison of two strings. The first being the original string and the second being the string stripped of prohibited tags. If the lengths do not match then the string contains prohibited tags – at which point an error would be thrown.

It’s a rather simple check to perform and can help prevent against XSS attacks.

Posted in PHP on the 28th April 2010


Your email address will not be published. Required fields are marked *