What are the best practices for handling sessions and global variables in PHP scripts to avoid warnings and errors?

When handling sessions and global variables in PHP scripts, it's important to properly initialize sessions and avoid using global variables whenever possible to prevent warnings and errors. To handle sessions, start the session at the beginning of the script and use session variables to store and retrieve data. To avoid using global variables, consider passing variables as parameters to functions or using classes and objects to encapsulate data.

// Start the session at the beginning of the script
session_start();

// Store data in session variables
$_SESSION['username'] = 'JohnDoe';

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

// Avoid using global variables whenever possible
function greetUser($username) {
    echo "Hello, $username!";
}

greetUser($username);