How can PHP sessions be effectively used to manage user authentication in a messaging system?

To manage user authentication in a messaging system using PHP sessions, you can store the user's authentication status in a session variable after successful login. This session variable can then be checked on each page to determine if the user is authenticated or not.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // User is authenticated, continue with messaging system
} else {
    // Redirect to login page
    header("Location: login.php");
    exit();
}