What is the best practice for creating a function that sets session variables in PHP?

When creating a function to set session variables in PHP, it is important to ensure that the session has started before attempting to set any variables. This can be achieved by checking if the session has already started using session_status() function. Additionally, it is good practice to sanitize any input data before setting it as a session variable to prevent security vulnerabilities.

function setSessionVariable($key, $value) {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    
    $_SESSION[$key] = $value;
}