What best practice should be followed when checking for authentication in PHP login functionality?

When checking for authentication in PHP login functionality, it is best practice to use prepared statements to prevent SQL injection attacks. This involves sanitizing user input and using parameterized queries to interact with the database securely. Additionally, storing passwords securely using hashing algorithms like bcrypt is crucial for protecting user data.

// Using prepared statements to check authentication
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch();

if ($user && password_verify($password, $user['password'])) {
    // Authentication successful
    $_SESSION['user_id'] = $user['id'];
    header('Location: dashboard.php');
    exit();
} else {
    // Authentication failed
    echo "Invalid username or password";
}