views:

93

answers:

2

So I have a form that accepts some input from a user that may at a later time be represented on the page.

The way I'm thinking of doing this from a security point of view is to take the input, apply the mysql_real_escape_string() function to all input, then insert using a prepared statement.

When retrieving the data, I'll do a htmlspecialchars() on it before presenting it on screen.

Will this be ok? Am I overlooking something important?

+4  A: 

Two things :

  • you must escape all input before sending it to the database ; for that :
    • mysql_real_escape_string is the right tool, if you are not using prepared statements
    • if you are using prepared statements, you do not need to escape by yourself : it'll be done automatically.
    • You must not do both, though : as @longneck clarified in his comment, if you are escaping yourself, and using prepared statements, which escape too, your string will be escaped twice -- and you do not want that.
  • Then, you must escape all output ; if your output format is HTML, htmlspecialchars or htmlentities are OK.

So, what you are doing seems OK to me for the ouput to HTML ; but you are doing more than necessary for the output to the DB.


As a sidenote : if you want to allow your users to use HTML, you can use a tool like HTMLPurifier -- it allows you to specify which tags/attributes are allowed or not.

Pascal MARTIN
just to clarify: you should either do mysql_real_escape_string() or use prepared statements. if you do both, the string will be double-escaped and will have to be pre-processed before being sent to the client.
longneck
@longneck : I've edited to insist on what you said ; thanks :-)
Pascal MARTIN
+1  A: 

Hi,

The methods you pointed are correct, and therefore must be used. And yes, your missing XSS Filtering. Check this site for XSS attack examples :

http://ha.ckers.org/xss.html

So, you'd better get a prevention system for this type of hacks, like a regex string. Here's some tutorials :

http://www.chipmunkninja.com/Helping-Prevent-XSS-Attacks-in-2@ http://shiflett.org/blog/2007/mar/allowing-html-and-preventing-xss

yoda