How can the $_SESSION variable be used to store and retrieve user data in PHP?

To store and retrieve user data in PHP using the $_SESSION variable, you can assign values to specific keys in the $_SESSION superglobal array to store user data, and then access those values by referencing the same keys. This allows you to persist user data across multiple pages during a user's session on your website.

// Start the session
session_start();

// Store user data in the $_SESSION variable
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'johndoe@example.com';

// Retrieve user data from the $_SESSION variable
$username = $_SESSION['username'];
$email = $_SESSION['email'];

// Output the retrieved user data
echo "Username: $username<br>";
echo "Email: $email";