How can PHP sessions be effectively utilized to store and retrieve information for user authentication?

To effectively utilize PHP sessions for user authentication, you can store user information such as username or user ID in session variables upon successful login. This information can then be used to verify the user's authentication status on subsequent pages by checking if the session variables are set. This helps in maintaining user authentication throughout their session on the website.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // User is authenticated, allow access to content
    echo "Welcome, ".$_SESSION['username']."!";
} else {
    // User is not authenticated, redirect to login page
    header("Location: login.php");
    exit();
}