einstein
einstein

Reputation: 13850

The safest way to avoid SQL injection in PHP?

I just wonder if this line of code is safe to use to avoid SQL injection?

// username and password sent from form 
$myusername=$_POST['loginUserName']; 
$mypassword=$_POST['loginPassword'];

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

Do I need to stripslashes?

Upvotes: 2

Views: 485

Answers (1)

Wyzard
Wyzard

Reputation: 34581

It's safer to use prepared statements, so that the (potentially malicious) values are separated from the query string, rather than relying on escaping. Read about PHP Data Objects.

Regarding stripslashes(), that should only be necessary if you have PHP's magic_quotes_gpc feature turned on, which you shouldn't because it's deprecated. If you want to be robust, though, do if (get_magic_quotes_gpc()) $myusername = stripslashes($myusername); so that it removes a layer of slashes if and only if one was added.

Upvotes: 8

Related Questions