What are the best practices for implementing a login system in PHP?

Implementing a secure login system in PHP involves hashing passwords, using prepared statements to prevent SQL injection, and setting up session management for authenticated users.

<?php
// Start session
session_start();

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate input data
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Check if the username and password match in the database
    // Use prepared statements to prevent SQL injection

    // If login is successful, set session variables
    $_SESSION['username'] = $username;
    $_SESSION['loggedin'] = true;

    // Redirect to the dashboard or homepage
    header("Location: dashboard.php");
    exit();
}
?>