How can data be stored and retrieved from sessions in PHP to maintain state between requests?

To store and retrieve data from sessions in PHP to maintain state between requests, you can use the $_SESSION superglobal array. To store data, you can assign values to specific keys in the $_SESSION array. To retrieve data, you can access the values stored in the $_SESSION array using the same keys.

// Start the session
session_start();

// Store data in the session
$_SESSION['username'] = 'JohnDoe';

// Retrieve data from the session
$username = $_SESSION['username'];

// Output the retrieved data
echo $username;