What are common pitfalls when handling login forms in PHP?
One common pitfall when handling login forms in PHP is not properly sanitizing user input, which can leave the application vulnerable to SQL injection attacks. To solve this issue, always use prepared statements and parameterized queries when interacting with the database to prevent malicious input from being executed as SQL commands.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// Prepare and execute a SQL query using prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->execute(['username' => $username, 'password' => $password]);
// Check if the user exists in the database
$user = $stmt->fetch();
if ($user) {
// User is authenticated, proceed with login
} else {
// Invalid credentials, show error message
}