What are the best practices for storing and retrieving variables using PHP sessions for data transfer between functions?

When storing and retrieving variables using PHP sessions for data transfer between functions, it is important to properly set, access, and unset session variables to avoid conflicts or security vulnerabilities. To do this, you can use the $_SESSION superglobal array to store and retrieve variables across different function calls within the same session.

// Start the session
session_start();

// Store a variable in the session
$_SESSION['username'] = 'JohnDoe';

// Retrieve the variable in another function
function getUsername() {
    return $_SESSION['username'];
}

// Unset the variable when it is no longer needed
unset($_SESSION['username']);