PHP Security Stripping Tags

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


strip_tags is a very powerful function if you know how to use it. As a method to prevent cross-site scripting attacks there are better methods, such as character encoding, but stripping tags is useful in some cases.

Basic Example

$string = '<b>Hello,<> please remove the <> tags.</b>';

echo strip_tags($string);

Raw Output

Hello, please remove the tags.

Allowing Tags

Say you wanted to allow a certain tag but no other tags, then you'd specify that in the second parameter of the function. This parameter is optional. In my case I only want the <b> tag to be passed through.

$string = '<b>Hello,<> please remove the <br> tags.</b>';

echo strip_tags($string, '<b>');

Raw Output

<b>Hello, please remove the  tags.</b>


HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags.

In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used in allowable_tags. For example, to allow both <br> and <br/>, you should use:

strip_tags($input, '<br>');

Got any PHP Question?