How can SQL Injection vulnerabilities be mitigated in PHP login scripts?
SQL Injection vulnerabilities in PHP login scripts can be mitigated by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps prevent malicious SQL code from being injected into the query and executed by the database.
// Using prepared statements 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();
if ($user) {
// Login successful
session_start();
$_SESSION['user_id'] = $user['id'];
echo 'Login successful';
} else {
// Login failed
echo 'Invalid username or password';
}
Related Questions
- How can PHP beginners effectively handle scenarios where user preferences need to be pre-selected in dropdown menus?
- What are the implications of using column names with special characters like "-" in SQL queries in PHP?
- What are common methods in PHP for manipulating text files, such as adding or deleting specific lines?