Ankit Sahu
Ankit Sahu

Reputation: 85

Fetching HTML code from the database as normal text

I have a program where user is posting information. The information posted by them is inserted into a data base. Now I am facing a problem when a user posts some HTML code. The code, when fetched from the database, acts as the HTML instead of normal text.

If a user posts <input type="text" it is inserted well in the database but when fetched a textbox appears. And if the user leaves the double quotes open <input type="text then the whole system crashes.

I don't know what to do. Please help me with this. Thanks.

Upvotes: 0

Views: 39

Answers (1)

David Chelliah
David Chelliah

Reputation: 1349

There are couple of ways to solve this problem

1, You can restrict the user from entering the HTML tags in the text area : Check out the free text editors javascript plugins like TinyMCE that will allow the users to enter text and prevent them from submitting the HTML tags.

2) You can allow the user to enter the HTML tags in the content, but use Regex to remove/replace/strip the tags from the output before persisting to database.

3) If you are using jquery, before submission take the textarea value using $("textarea").text() - this will automatically strip the tags and just takes the text entered by the user

4) If you are free allowing user to key-in anything and saving it to database. Then before displaying do HTML encode of the special HTML characters or you can say that as escaping the HTML special characters (e.g., '<' should be replaced by "&lt;"). This will make the HTML textbox appear as exactly as user typed in. [Live example : Stackoverflow's answer textarea]

Upvotes: 1

Related Questions