What are the best practices for accessing session variables in included PHP files?

When accessing session variables in included PHP files, it is important to first start the session using session_start() at the beginning of each file that needs access to session variables. This ensures that the session is properly initialized and the variables can be accessed. It is also recommended to check if the session variable exists before accessing it to avoid errors.

<?php
// Include this at the beginning of each PHP file that needs access to session variables
session_start();

// Check if the session variable exists before accessing it
if(isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
    echo "Welcome, $username!";
} else {
    echo "Session variable 'username' not set.";
}
?>