What is the purpose of starting a session in PHP and when is it needed?

Starting a session in PHP is necessary when you want to store and access session data across multiple pages of a website. Sessions allow you to store user-specific information and maintain state between requests. By starting a session, you can create variables that persist throughout the user's visit to the website.

<?php
session_start();

// Set session variables
$_SESSION['username'] = 'john_doe';
$_SESSION['email'] = 'john.doe@example.com';

// Access session variables
echo 'Username: ' . $_SESSION['username'];
echo 'Email: ' . $_SESSION['email'];
?>