What improvements can be made to the login functionality in the PHP code to enhance security and efficiency?
To enhance security and efficiency in the login functionality of PHP code, it is recommended to implement password hashing using PHP's password_hash() function and password_verify() function for password authentication. This will securely store passwords in a hashed format and verify them during login. Additionally, using prepared statements with parameterized queries can prevent SQL injection attacks.
// Improved login functionality with password hashing and prepared statements
// Password hashing
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// Prepare SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$user = $stmt->fetch();
if ($user && password_verify($_POST['password'], $user['password'])) {
// Login successful
} else {
// Login failed
}