What best practices should be followed when implementing login functionality in PHP using sessions?

When implementing login functionality in PHP using sessions, it is important to follow best practices to ensure security and reliability. This includes properly sanitizing user input, using password hashing for storing passwords, and validating user credentials before creating a session.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize user input
    $username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
    $password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);

    // Validate user credentials (example only, implement your own validation logic)
    if ($username === "admin" && password_verify($password, '$2y$10$9mXrBk7NwF2ZrD6qHk9mOuV3IY2X7kQ2tni6qGzA3mHn2o3gXJ3A2')) {
        // Set session variables
        $_SESSION["username"] = $username;

        // Redirect to dashboard or home page
        header("Location: dashboard.php");
        exit();
    } else {
        echo "Invalid username or password";
    }
}
?>