What are common pitfalls when using PHP for login scripts, especially when it comes to handling user input?

One common pitfall when using PHP for login scripts is not properly sanitizing and validating user input, which can leave the system vulnerable to SQL injection or cross-site scripting attacks. To solve this issue, always use prepared statements with parameterized queries to prevent SQL injection, and use functions like htmlspecialchars() to prevent cross-site scripting attacks.

// Example of using prepared statements with parameterized queries to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute(['username' => $username, 'password' => $password]);
$user = $stmt->fetch();

// Example of using htmlspecialchars() to prevent cross-site scripting attacks
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);