What are best practices for securely working with sessions in PHP, especially when checking if a user is logged in?

When working with sessions in PHP to check if a user is logged in securely, it is important to use session hijacking prevention techniques such as regenerating the session ID after a successful login and storing sensitive user information in the session data. Additionally, always validate user input and sanitize data to prevent injection attacks.

// Start the session
session_start();

// Regenerate the session ID to prevent session fixation attacks
session_regenerate_id();

// Check if the user is logged in
if(isset($_SESSION['user_id'])) {
    // User is logged in
    echo 'User is logged in.';
} else {
    // User is not logged in
    echo 'User is not logged in.';
}