NSF
NSF

Reputation: 2549

Is this SQL query safe from injection?

The code below is written in php:

$user = addslashes($_POST['user']);
$pwd = addslashes($_POST['pwd']);

$query = "SELECT * FROM userdata WHERE UserName='$user' AND Password=PASSWORD('$pwd')";

the query will then be sent to mysql Is there anything more I need to take care of?

Please point out.

Upvotes: 1

Views: 774

Answers (4)

Afshin Mehrabani
Afshin Mehrabani

Reputation: 34919

Protecting against SQL injection is easy:

Filter your data.

This cannot be overstressed. With good data filtering in place, most security concerns are mitigated, and some are practically eliminated.

Quote your data.

If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type.

Escape your data.

Sometimes valid data can unintentionally interfere with the format of the SQL statement itself. Use mysql_escape_string() or an escaping function native to your particular database. If there isn't a specific one, addslashes() is a good last resort.

Read more: http://phpsec.org/projects/guide/3.html#3.2

Upvotes: 2

Code Magician
Code Magician

Reputation: 23972

Nope.

The reason is that while a single quote ' is not the only char that break a sql query, quotes are the only chars escaped by addslashes().

Better: use mysql_real_escape_string

$user = mysql_real_escape_string($_POST['user'], $conn);
$pwd = mysql_real_escape_string($_POST['pwd'], $conn);

$query = "SELECT * FROM userdata WHERE UserName='$user' AND Password=PASSWORD('$pwd')";

Best: use PDO and prepared statements

$stmt = $dbh->prepare("SELECT * FROM userdata WHERE UserName=':user' AND Password=PASSWORD(':pass')");
$stmt->bindParam(':user', $user);
$stmt->bindParam(':pass', $pass);

Upvotes: 5

Sarfraz
Sarfraz

Reputation: 382608

No it's not safe, use mysql_real_escape_string at minimum:

$user = mysql_real_escape_string($_POST['user']);
$pwd = mysql_real_escape_string($_POST['pwd']);

And for better security go for prepared statements.

Best Options:

You may ask which one to choose, check out:

Upvotes: 5

John Conde
John Conde

Reputation: 219794

No. You should not be using addslashes() to escape your data. That's been obsolete for years. You should be either:

Plus using MySQL's Password() function is also poor pracdtive. Use hashes with salts. Bcrypt is my recommendation. Also, check out PHPass.

Upvotes: 3

Related Questions