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

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.

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

Comments are closed.

Scroll to Top