What are best practices for handling session variables in PHP to ensure they are passed correctly?

Session variables in PHP should be properly initialized, accessed, and unset to ensure they are passed correctly between pages. It is important to start the session at the beginning of each page where session variables are used, and to unset them when they are no longer needed to free up server resources. Additionally, using session_regenerate_id() can help prevent session fixation attacks by generating a new session ID.

<?php
// Start the session
session_start();

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

// Access the session variable
echo $_SESSION['username'];

// Unset the session variable
unset($_SESSION['username']);

// Regenerate the session ID
session_regenerate_id(true);
?>