How can a session variable be stored and accessed in PHP for user authentication?

To store and access a session variable for user authentication in PHP, you can use the $_SESSION superglobal array. When a user logs in, you can set a session variable with their user ID or any other relevant information. This session variable can then be checked on subsequent pages to verify the user's authentication status.

// Start the session
session_start();

// Set the session variable upon user login
$_SESSION['user_id'] = $user_id;

// Access the session variable on other pages to verify user authentication
if(isset($_SESSION['user_id'])) {
    // User is authenticated
} else {
    // User is not authenticated
}