What are the common pitfalls to avoid when working with session data in PHP, especially when dealing with user authentication?

Common pitfalls to avoid when working with session data in PHP, especially when dealing with user authentication, include not properly validating and sanitizing user input, not securely storing session data, and not properly handling session expiration and regeneration.

// Validating and sanitizing user input
$username = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password']) : '';

// Storing session data securely
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;

// Handling session expiration and regeneration
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > 1800) {
    session_regenerate_id(true);
    $_SESSION['last_activity'] = time();
}