How can sessions be effectively used to store and retrieve data in PHP applications?

Sessions can be effectively used to store and retrieve data in PHP applications by starting a session, setting session variables with the data you want to store, and then accessing that data by retrieving the session variables when needed. This allows you to persist data across multiple pages or requests for a specific user.

// Start the session
session_start();

// Set session variables
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'johndoe@example.com';

// Retrieve session variables
$username = $_SESSION['username'];
$email = $_SESSION['email'];

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