What best practices should be followed when designing a PHP login form for secure user authentication?

When designing a PHP login form for secure user authentication, it is important to follow best practices such as using prepared statements to prevent SQL injection, hashing passwords before storing them in the database, implementing CSRF tokens to prevent cross-site request forgery, and using SSL to encrypt data transmission.

// Sample PHP code snippet for secure user authentication

// Start a session
session_start();

// Validate user input and prevent SQL injection
$username = $_POST['username'];
$password = $_POST['password'];

// Hash the password before storing it in the database
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Check if the user exists in the database
// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

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