What role does the SESSION variable play in maintaining user data in PHP scripts?

The SESSION variable in PHP is used to store user data across multiple pages or requests. It allows for maintaining user-specific information such as login status, shopping cart items, or preferences. By using the SESSION variable, you can easily access and manipulate user data throughout a user's session on your website.

// Start the session
session_start();

// Store user data in the SESSION variable
$_SESSION['username'] = 'JohnDoe';
$_SESSION['cart'] = ['item1', 'item2', 'item3'];

// Retrieve user data from the SESSION variable
$username = $_SESSION['username'];
$cartItems = $_SESSION['cart'];

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