How can usernames and passwords be securely stored and retrieved in PHP sessions?

Usernames and passwords should never be stored directly in PHP sessions as they can be easily accessed by malicious users. Instead, passwords should be securely hashed and stored in a database, while usernames can be stored in the session. When retrieving the username from the session, always validate and sanitize the input to prevent any potential security risks.

// Store username in session
$_SESSION['username'] = $username;

// Hash and store password in database
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Store $hashed_password in the database

// Retrieve username from session
$username = isset($_SESSION['username']) ? $_SESSION['username'] : null;
// Validate and sanitize $username before using it