How can SQL injection vulnerabilities be addressed in the PHP login script?
SQL injection vulnerabilities in a PHP login script can be addressed by using prepared statements or parameterized queries to prevent malicious SQL code from being injected into the database. This approach helps sanitize user input and ensures that only safe, validated data is used in SQL queries.
// Using prepared statements to prevent SQL injection in PHP login script
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);
// Execute the statement
$stmt->execute();
// Check if a user with the provided credentials exists
$user = $stmt->fetch();
if ($user) {
// User authenticated successfully
echo 'Login successful!';
} else {
// Invalid credentials
echo 'Invalid username or password.';
}
Related questions
-
Fatal error Call to undefined function domxml_open_mem()
-
classes PHP password protection
-
What are common errors that can occur when trying to display SQL query results in a table using PHP?SQL query PHP table display