What are some best practices for implementing a registration/login function in PHP, especially in regards to managing user sessions?

Issue: When implementing a registration/login function in PHP, it is essential to properly manage user sessions to ensure secure access and data protection. Code snippet:

// Start session
session_start();

// Check if user is already logged in
if(isset($_SESSION['user_id'])) {
    // User is already logged in, redirect to home page
    header('Location: home.php');
    exit;
}

// Register user function
function registerUser($username, $password) {
    // Add code to validate and sanitize input data

    // Add code to hash the password before storing it
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Add code to store user data in database
    // Example: $query = "INSERT INTO users (username, password) VALUES ('$username', '$hashedPassword')";
    // Execute query and handle success/error
}

// Login function
function loginUser($username, $password) {
    // Add code to validate and sanitize input data

    // Add code to fetch user data from database
    // Example: $query = "SELECT * FROM users WHERE username='$username'";
    // Execute query and handle result

    // Add code to verify password
    if(password_verify($password, $hashedPassword)) {
        // Password is correct, set session variables and redirect to home page
        $_SESSION['user_id'] = $user_id;
        header('Location: home.php');
        exit;
    } else {
        // Password is incorrect, display error message
        echo "Invalid username or password";
    }
}

// Logout function
function logoutUser() {
    // Unset session variables
    session_unset();
    // Destroy session
    session_destroy();
    // Redirect to login page
    header('Location: login.php');
    exit;
}