How can session variables be used as an alternative to passing variables through URLs in PHP?

When passing variables through URLs in PHP, there is a risk of exposing sensitive information or cluttering the URL with unnecessary parameters. Session variables provide a more secure and cleaner alternative for storing and accessing data across multiple pages. By setting session variables, you can easily access the data without the need to pass it through URLs.

// Start the session
session_start();

// Set a session variable
$_SESSION['username'] = 'JohnDoe';

// Access the session variable on another page
session_start();
echo $_SESSION['username'];