StackExchange
7
votes

How do I securely handle user login in PHP with prepared statements?

Asked 50 mins ago
by JohnSmith php, security

I need to implement user authentication in PHP but I'm unsure about the best way to handle security concerns. I understand that using prepared statements is important, but I'm not clear on how to properly implement this in the login process. Should I be checking for any common user input patterns that could indicate SQL injection attempts first? Are there other security considerations I should be aware of when building login functionality?

2 Answers

12
by JaneDoe · 40 mins ago

Here's how to safely implement login using PHP:

  1. Create a prepared statement using PDO or MySQLi with placeholders for username/password
  2. Never validate against SQL keywords in user input (just prevent injection)
  3. Hash passwords with password_hash() and verify with password_verify()
  4. Implement rate limiting to prevent brute-force
<?php
$stmt = $pdo->prepare("SELECT password FROM users WHERE username=?");
$stmt->execute(["$_POST['username']"]);
$user = $stmt->fetch();
if ($user && password_verify($_POST['password'], $user['password'])) {
    // Login success
}
?>
Add a comment
7
by SecureDev · 6 mins ago

Use the built-in PHP functions:

  • filter_var() to validate emails/inputs
  • password_hash() instead of storing plain Bcrypt
  • Always use HTTPS
<?php
if (isset($_POST['login'])) {
    $stmt = $pdo->prepare("SELECT password FROM users WHERE username = ? LIMIT 1");
    $stmt->bindValue(1, $_POST['username']);
    $stmt->execute();
    $user = $stmt->fetch();
    
    if ($user && password_verify($_POST['password'], $user['password'])) {
        echo "Login success";
    }
}
?>
Your Answer