How can the use of isset() function help in preventing errors related to session variables in PHP scripts?

When accessing session variables in PHP scripts, it is essential to check if the variable is set before using it to prevent errors. The isset() function can be used to determine if a session variable has been set or not, allowing for safe access without causing undefined variable errors.

session_start();

// Check if the session variable is set before using it
if(isset($_SESSION['username'])){
    $username = $_SESSION['username'];
    echo "Welcome back, $username!";
} else {
    echo "Please log in to access this page.";
}