0

I currently have this PHP code right now for authentication and I would like to figure out if it's vulnerable to a MySQL injection. Specifically if someone can return fake data with an UNION or other attack and therefore fake the login. I am currently using mysqli_real_escape_string to try to prevent trivial attacks and also attempt to sanitize the request. However, is this code perfectly safe due to the use of mysqli_real_escape_string or is there a security flaw?

$email = mysqli_real_escape_string($database_connection, $_POST["email"]);
$pass = mysqli_real_escape_string($database_connection, $_POST["pass"]);
$query = "SELECT * FROM auths WHERE email='$email' AND pass='$pass'";
$query_result = mysqli_query($database_connection, $query);

if(mysqli_num_rows($query_result) === 1) 
{
    // User is logged in.
}
else
{
    die("Unauthorized");
}
7
  • 7
    Mysqli prepared statements If you're accepting user data, do not use anything else. Period. Commented Nov 3, 2014 at 19:45
  • 1
    It's perfectly safe, but it's best if you use prepared statements. Then you can just simply forget about escaping the data. Commented Nov 3, 2014 at 19:46
  • 1
    Ohgodwhy: How would the injection attack work in this case? What would be an example of bad input? Commented Nov 3, 2014 at 19:46
  • Example here. Do not use mysqli_real_escape_string to protect against SQL injection. stackoverflow.com/questions/5741187/… Commented Nov 3, 2014 at 19:48
  • @user4819 Just have a look at the thread that was linked by Svein for an example. There are other examples on the web as well. It is not an end all to be all protection measure, and it should not be purported as such. Commented Nov 3, 2014 at 19:50

1 Answer 1

3

Forget mysqli_real_escape_string. Simply use prepared statements

$conn = new mysqli('host', 'user', 'pass', 'database');        
$stmt = $conn->prepare('select * from auths where email=? and pass=?');
$stmt->bind_param('ss', $_POST['email'], $_POST['pass']);
$stmt->execute();
if($stmt->num_rows > 0):
    //user is logged in
else:
    die('Unauthorized');
endif;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.