What is the potential issue with the login function in the provided PHP code?
The potential issue with the login function in the provided PHP code is that it is vulnerable to SQL injection attacks. To solve this issue, you should use prepared statements with parameterized queries to prevent SQL injection.
// Fix for login function using prepared statements
function login($username, $password) {
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// User authenticated successfully
return true;
} else {
// Authentication failed
return false;
}
$stmt->close();
$conn->close();
}
Related Questions
- What are some best practices for avoiding issues with array_merge() when trying to remove duplicate values from an array in PHP?
- What are some common pitfalls when using regular expressions to extract image URLs from HTML content in PHP?
- How can the issue of the warning messages related to readdir() and closedir() functions be resolved in the PHP script?