How can PHP developers prevent SQL injection vulnerabilities in login scripts?
To prevent SQL injection vulnerabilities in login scripts, PHP developers should use prepared statements with parameterized queries instead of directly interpolating user input into SQL queries. This approach ensures that user input is treated as data rather than executable code, making it impossible for attackers to inject malicious SQL commands.
// Using prepared statements to prevent SQL injection in login script
// Assuming $username and $password are user inputs
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare the SQL query using placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
// Bind the user input to the placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// Execute the query
$stmt->execute();
// Check if a row was returned
if ($stmt->rowCount() > 0) {
// User authenticated successfully
} else {
// Invalid credentials
}