Are there any best practices for managing user sessions and displaying logged-in users in PHP?

When managing user sessions and displaying logged-in users in PHP, it is important to securely store session data and properly authenticate users. One best practice is to use PHP's built-in session handling functions to start, manage, and destroy sessions. Additionally, when displaying logged-in users, always validate user credentials before showing any sensitive information.

// Start the session
session_start();

// Check if the user is logged in
if(isset($_SESSION['user_id'])){
    // Display logged-in user information
    echo 'Welcome, ' . $_SESSION['username'];
} else {
    // Redirect to login page if user is not logged in
    header('Location: login.php');
    exit();
}