tags:

views:

124

answers:

5

What is the most secure way to stop users adding html or javascript to a field. I am adding a youtube style 'description' where users can explain their work but I don't want anything other than plain text in there and preferable none of the htmlentities rubbish like '<' or '>'.

Could I do something like this:

$clean = htmlentities($_POST['description']);

if ($clean != $_POST['description']) ... then return the form with an error?
+5  A: 

Have you seen strip_tags?

Daniel A. White
You all answered in the same minute, but according to 'oldest' you were first. But thank you all for your answers.
Mark
+2  A: 

strip_tags() would probably be the best bet.

You don't need to check the cleaned code vs the original and throw an error. As long as it is cleaned, you should be able to display it. Just throw away the original comment. You can put a note under the textbox saying that no html is allowed if you want to make it more user friendly.

Cryophallion
+2  A: 

Use strip_tags() instead htmlentities().
And the method is ok.

hsz
A: 

Also don't forget mysql_real_escape_string() if you are storing data in MySQL.

amindzx
+1  A: 

htmlspecialchars(), if used properly (see comments), is the safest way to ensure plain text. There is no way to inject any HTML or JavaScript when the output has all the HTML special characters escaped. If you use strip_tags, you will prevent your users from using completely legitimate characters.

Ignas R
@Ignas - This is wrong, using htmlspecialchars() without specifying the character encoding, XSS attacks that use UTF-7 are possible.
Jay Zeng
Then, doesn't it also mean that `strip_tags` is also vulnerable to that? But anyway, thanks. I've corrected my answer.
Ignas R
@Ignas - I honestly don't know if strip_tags() is vulnerable as well as it doesn't take encoding as parameter. I will have to play around this :)
Jay Zeng