views:

248

answers:

3

"We should never trust user's input", this is what I read from somewhere on the web.

Currently I have a web form, they enter their username and emails. For username field, how to control, check and prevent mysql injection?? Currently, in my php script I only do this:

$username = mysql_real_escape_string($_POST['username']); // prevent mysql injection

I saw some tutorials, before the mysql_real_escape_string function, they include other functions like, htmlentities, etc (could not remember what it is, and I cant found it now, sigh)

Is this a must to include the so called "htmlentities" function before mysql_real_escape_string??

What is your method you usually use for checking user's input data?

Oh ya, some other functions:

stripslashes();
serialize();
urlencode();

Must i include those?

+11  A: 

You're doing it right, as far as putting your data into the database is concerned. You're protected against SQL injection attacks.

htmlentities() and htmlspecialchars() aren't relevant to SQL injection attacks; they're relevant to XSS attacks, which is a whole other topic you should look into, and is a relevant issue if you're displaying user input back out to the web.

chaos
Couldn't have put it better myself. http://en.wikipedia.org/wiki/Cross-site_scripting
Artem Russakovskii
what are the others attack beside sql injection and XSS?? if i include the htmlentities() and htmlspecialchars() will it prevent XSS attacks??
jingleboy99
For other forms of attack, see this question: http://stackoverflow.com/questions/438073/do-stackoverflow-users-agree-with-the-cwe-sans-top-25-most-dangerous-programming. htmlentities() and htmlspecialchars() should be used when you're producing output, not receiving input, and you wouldn't use both at the same time. In order to have much hope of any of these methods actually protecting you, you will need to treat them less as magic rituals and work more to understand *what* they do, and *why* and *how* they should be applied.
chaos
+1  A: 

like @chaos said is right

you can also use database abstraction layers, like pdo that will escape the paramaters for you

bumperbox
+1  A: 

You could also look at using prepared statements (I think equivalent to parameterized queries for SQL Server), which further reduces the attack surface.

Si