PHP: Allow Specific HTML Tags in Text Input Controls of HTML Forms, <textarea>, <input type=”text” />

by Yang Yang on February 15, 2010

Share This Article:
Subscribe to Kavoir: blog feed

Textarea and text input are common html form controls that accept text input. They can be a security challenge as they allow the user to enter anything they want. If you just go about using whatever data the user has entered, your application is anything but secure. Some sort of filtering / white-listing must be in place to protect the integrity of the application and you need to permit or allow only a few special HTML tags in the textarea control of the HTML forms.

The simplest way is to denounce any attempts to add HTML tags in the text box control is the PHP function strip_tags():

$all_tags_filtered = strip_tags($_POST['message']);

Wherein $_POST['message'] is the text just submitted by a user, containing all sorts of HTML tags. Thanks to the function strip_tags(), all the tags are now gone in $all_tags_filtered. The data in $all_tags_filtered is safe to use as it’s plain text.

However, there are times when you want to keep a few simple tags for the user’s convenience, such as <p>, <strong> and <em>. To do this, just feed a second parameter to the function strip_tags():

$some_tags_filtered = strip_tags($_POST['message'], '<p><strong><em>');

So <p> elements, <strong> elements and <em> elements are kept intact while all the other tags are gotten rid of in $some_tags_filtered.

One important thing to note is that strip_tags() does not check the attributes of the allowed HTML tags. The attributes of the allowed HTML elements such as style="" and onmouseover="" are kept as they are in the filtered results which may lead to other security problems. You have to use regular expressions to erase them out and block attached malicious attempts.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 5 comments… read them below or add one }

v March 19, 2010 at 4:52 am

hii
hiii

Reply

Stefan April 27, 2010 at 2:19 am

Testing utf8
åäö

Reply

Joe August 30, 2010 at 3:48 am

Great article on HTML. Have you read anything on the new html 5 standard thats released? Supposedly its suppose to replace flash all together. Whats your thoughts on that topic?

Joe – Email Marketing Software

Reply

3roses January 24, 2011 at 8:21 pm

trying.. bold

Reply

Keith December 9, 2011 at 7:00 pm

Thank you for this!

Reply

Leave a Comment

Previous post:

Next post: