How can PHP sessions be used to manage user interactions and maintain state across multiple pages?

PHP sessions can be used to manage user interactions and maintain state across multiple pages by storing user-specific information on the server. This allows the server to identify each user and maintain their session data as they navigate through different pages of the website.

// Start the session
session_start();

// Set session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'exampleuser';

// Retrieve session variables on other pages
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// Destroy the session when the user logs out
session_destroy();